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);
2

4 Answers 4

4

Using preg_replace()

$name = preg_replace('#\s+#', ' ', $rawName);
Sign up to request clarification or add additional context in comments.

6 Comments

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 $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.
You got two things to do. 1. Replace all multispaces to one and 2. Replace all spaces to hyphen. Right?
@jmenezes If thats the case, can you please try this one only replacing the line you got there - $name = preg_replace('#\s+#', '-', $rawName);
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?
|
0

Try this : that should kee only one space between words

{
 $var = str_replace(' ','',$var);
}

1 Comment

that would only reduce one space from each group and all the single spaces will vanish!...
0

Try this

$str = preg_replace( "/\s+/", " ", $data );

Comments

-1
$output = preg_replace('!\s+!', ' ', $input);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.