Let str_replace effect one time

Discussion in 'PHP' started by Adulu, Jan 28, 2010.

  1. #1
    <?php
    $names="my site your site not their site";
    
    $a1 = str_replace("site", "<a href='http://forums.digitalpoint.com'>site</a>", "$names");
    
    echo $a1;
    ?> 
    PHP:
    result:
    ----------

    how to let str_replace effect one time?

    i would like below result
    thank you
     
    Adulu, Jan 28, 2010 IP
  2. bitist

    bitist Peon

    Messages:
    28
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    PHP documentation says:
    str_replace — Replace all occurrences of the search string with the replacement string

    So, to replace only one occurrence you need another way, another function:
    preg_replace

    <?php
    $names="my site your site not their site";
    
    $a1 = str_replace("site", "<a href='http://forums.digitalpoint.com'>site</a>", "$names");
    echo $a1;
    
    echo "<br /><br /><br />";
    $a1 = preg_replace("/site/", "<a href='http://forums.digitalpoint.com'>site</a>", "$names", 1);
    echo $a1;
    ?>
    PHP:
     
    bitist, Jan 28, 2010 IP
  3. Adulu

    Adulu Peon

    Messages:
    2,791
    Likes Received:
    43
    Best Answers:
    0
    Trophy Points:
    0
    #3
    It's working:D
    thank you so much bitist
     
    Adulu, Jan 29, 2010 IP