How do I remove spaces from a string in PHP?

Solution:

You can remove all spaces from a string using preg_replace():


$abcd = "this is a test";

// Option 1: remove spaces explicitly
$abcd = preg_replace('/( *)/', '', $abcd);
echo $abcd . "\n"; // Output: thisisatest

// Option 2: remove all whitespace characters
$abcd = preg_replace('/\s/', '', $abcd);
echo $abcd . "\n"; // Output: thisisatest

📌 PHP preg_replace() Manual

Both approaches will strip spaces; the second one also removes tabs, newlines, and other whitespace characters.