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,846
  • 7
  • 27
  • 40
  • 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
  • 4,927
  • 6
  • 30
  • 50
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
  • 35,828
  • 9
  • 90
  • 101
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
  • 37,963
  • 8
  • 65
  • 101
0

You can use regular expressions:

$name = preg_replace("#\s+#", "_", $name);
Guillaume Poussel
  • 9,282
  • 1
  • 32
  • 41