replacing spaces with just one "_"
Probably the cleanest and most readable solution:
preg_replace('/[[:space:]]+/', '_', $name);
This will replace all spaces (no matter how many) with a single underscore.
You can accomplish this with a regular expression:
[ ]+
This will match "one or more space characters"; if you want "any whitespace" (including tabs), you can instead use \s+
.
Using this with PHP's preg_replace()
:
$name = preg_replace('/[ ]+/', '_', $name);
Use preg_replace()
:
$name = preg_replace('/ +/', '_', $name);
+
in regex means "repeated 1 or more times" hence this will match [SPACE]
as well as [SPACE][SPACE][SPACE]
.