String replace question

I’m confused. I must have read the following snippet somewhere and just assumed (stupid, that) that it actually does replace multiple whitespace characters with single spaces, as was advertised.

str_replace(' ', ' ', ...etc.

Instead, I found that I’ve had to resort to the more intensive preg replace:

preg_replace('/\\s+/', ' ', ...etc.

So what dumb thing did I do wrong with that string replace format?

Nothing. String Replace has no logic, it’s a replacement of one string literal to another. So you were basically replacing every white space with another white space.

In your situation, you must use regex as you found out.

Hmmm, OK. Thanks for the reply, wonshikee.

I wonder what gives with the snippets that suggest using string replace, though. I’ve seen it more than once (including the users’ notes in the PHP manual, IIRC). You’d think that people would check code before publishing it.

Technically, it should be something like:

$string = preg_replace('/\\s{2,}/', ' ', $string);

This way, you’ll replace 2 or more spaces with one. If you replace every instance of one or more space with a single space, then that’s a lot more replacing than necessary.
By the way, according to what i saw in the PHP str_replace user notes, they put two spaces in str_replace, not one. i think that might be your problem. But still, I think the preg_replace is better.

Thanks for the tip. That’ll be useful for textareas.

Re: the PHP manual; I think that it was on the page for trim that I saw str replace mentioned. Not sure.