str_replace help

Discussion in 'PHP' started by carl_in_florida, Nov 26, 2007.

  1. #1
    I have a dg call that i want to do str_replace to several parts of the text.

    How do i do str_repalce several times to the same text. like if I grabbed a story from the database and I wanted to replace every boston with miami and every Stan with Bob and every fly with drive how would i do that?

    I can do one with :
    echo str_replace("boston", "miami", "$text");
    PHP:
    but how do you do it multiple times
     
    carl_in_florida, Nov 26, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    echo str_replace(
        array("boston", "Stan"),
        array("miami", "Bob"), $text);
    
    PHP:
     
    nico_swd, Nov 26, 2007 IP
    carl_in_florida likes this.
  3. moodswing

    moodswing Peon

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #3
    $text1 = str_replace('boston', 'miami', $text);
    $text2 = str_replace('Stan', 'Bob', $text1);
    $text3 = str_replace('fly", 'drive', $text2);

    echo $text3;
     
    moodswing, Nov 26, 2007 IP
    carl_in_florida likes this.
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    This is a bad practice. Now you have 3 variables which hold (almost) exactly the same as the one you need. Plus you have 2 more function calls. It's unnecessary slow, and takes more resources.

    Note that in PHP, you can overwrite variables anytime you want.
     
    nico_swd, Nov 26, 2007 IP
  5. carl_in_florida

    carl_in_florida Active Member

    Messages:
    1,066
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    90
    #5
    Thanks for the help. +rep for everyone
     
    carl_in_florida, Nov 26, 2007 IP