0

How can I add something to replace all multiple spaces in a string, with only single spaces in the below regex?. Everything else in the below code needs to remain as it is. I'm only trying to add the replace multiple spaces part.

The other part in there replaces multiple hyphens with a single one.

$name = preg_replace('#[ -]+#', '-', $rawName);
jmenezes
  • 1,888
  • 6
  • 28
  • 44
  • possible duplicate of [php Replacing multiple spaces with a single space](http://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space) – mario Nov 13 '13 at 05:56
  • Did you see this ? : http://stackoverflow.com/questions/2326125/remove-multiple-whitespaces-in-php – Raiyan Nov 13 '13 at 05:57

4 Answers4

3

Using preg_replace()

$name = preg_replace('#\s+#', ' ', $rawName);
Neel Basu
  • 12,638
  • 12
  • 82
  • 146
Jithin
  • 2,594
  • 1
  • 22
  • 42
  • Actually, I was asking how to add this to the existing code I have. Now it seems all my hyphens are missing. So I did this: `echo preg_replace('#[ -\s]+#','-',$rawName);` but is this the correct way to do it? – jmenezes Nov 13 '13 at 06:06
  • @jmenezes `$name = preg_replace('#[ -]+#', '-', $rawName);` will replace all spaces to hyphen. Your question was how to replace multiple spaces to one. Put the answer line posted above, the `$name = preg_replace('#[ -]+#', '-', $rawName);` line. – Jithin Nov 13 '13 at 06:09
  • You got two things to do. 1. Replace all multispaces to one and 2. Replace all spaces to hyphen. Right? – Jithin Nov 13 '13 at 06:16
  • @jmenezes If thats the case, can you please try this one only replacing the line you got there - `$name = preg_replace('#\s+#', '-', $rawName);` – Jithin Nov 13 '13 at 06:17
  • The solution in your second comment works nicely. Just one small question, is it ok to do it the way I posted in my first comment? – jmenezes Nov 13 '13 at 06:41
  • @jmenezes : It will work. Actually the method you used in first place also need to work. But keep in mind that what you put inside the `[]` brackets inside a regex is character set. So it will match it as characters except the characters with \ . `'#[-\s]+#'` will work. You need to only use `[ ]` or `[\s]`. – Jithin Nov 13 '13 at 06:51
0

Try this : that should kee only one space between words

{
 $var = str_replace(' ','',$var);
}
Neel Basu
  • 12,638
  • 12
  • 82
  • 146
0

Try this

$str = preg_replace( "/\s+/", " ", $data );
Muhammad Rashid
  • 563
  • 1
  • 6
  • 25
-1
$output = preg_replace('!\s+!', ' ', $input);
Neel Basu
  • 12,638
  • 12
  • 82
  • 146