2

I'm trying to replace all of the consecutive spaces with just one underscore; I can easily replace one space with "_" by using the following line of code:

str_replace(" ", "_",$name);

Evan I can replace one spaces with "_" by following line of code:

str_replace("  ", "_",$name);

But the problem is I don't know how many blank spaces I have to check!

If my question is not clear please let me know which part you need more clarification.

Thanks

user385729
  • 1,924
  • 9
  • 29
  • 42
  • possible duplicate of [php Replacing multiple spaces with a single space](http://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space) – dang Oct 22 '13 at 13:32

4 Answers4

6

Probably the cleanest and most readable solution:

preg_replace('/[[:space:]]+/', '_', $name);

This will replace all spaces (no matter how many) with a single underscore.

subZero
  • 5,056
  • 6
  • 31
  • 51
3

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);
newfurniturey
  • 37,556
  • 9
  • 94
  • 102
2

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].

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
0

You can use regular expressions:

$name = preg_replace("#\s+#", "_", $name);
Guillaume Poussel
  • 9,572
  • 2
  • 33
  • 42