2

This is the string i'm trying to replace white spaces between the words with "-".

$mystring = "Color red, Color blue, Color black";
$newstring = str_replace(' ', '-', $mystring);

What i want to achieve, using the str_replace function, is:

"Color-red, Color-blue, Color-black";

But that returns:

"Color-red,-Color-blue,-Color-black";

I guess i need a condition that replaces white spaces "not after the comma" or "between two words". But i have no idea. Any suggestion?

1 Answer 1

4

(?<!,)\s

That uses a negative lookbehind to match all spaces (\s) that aren't followed by a ,.

preg_replace("/(?<!,)\s/", '-', $mystring);

Play with the regex here.

Sign up to request clarification or add additional context in comments.

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.