SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Zealot
    Join Date
    Sep 2009
    Posts
    118
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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.

    PHP Code:
    str_replace(' '' ', ...etc
    Instead, I found that I've had to resort to the more intensive preg replace:

    PHP Code:
    preg_replace('/\s+/'' ', ...etc
    So what dumb thing did I do wrong with that string replace format?

  2. #2
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    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.

  3. #3
    SitePoint Zealot
    Join Date
    Sep 2009
    Posts
    118
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.

  4. #4
    SitePoint Wizard bronze trophy devbanana's Avatar
    Join Date
    Apr 2006
    Location
    Pennsylvania
    Posts
    1,736
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Technically, it should be something like:

    PHP Code:
    $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.
    Laudetur Iesus Christus!
    Christ's Little Flock
    Jesus is the Good Shepherd

  5. #5
    SitePoint Zealot
    Join Date
    Sep 2009
    Posts
    118
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •