preg replace first instance of a value and relace the rest otherwise

Discussion in 'PHP' started by ade92uk, Jan 27, 2009.

  1. #1
    Hi, i would like to use preg replace to replace the first instance of a word with another word and teh remainigninstances with a blank space. Please help, what i have so far is:

    
    $s[] = '#Refrain#si';
    $r[] = '';
    $result = preg_replace($s, $r, $results);
    Code (markup):
    The code above works and replaces all instances of the word refrain with the blank space, buti want to replace the first instance of the word with something else.
     
    ade92uk, Jan 27, 2009 IP
  2. yoavmatchulsky

    yoavmatchulsky Member

    Messages:
    57
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    48
    #2
    you can run it twice

    the first time, use preg_replace with the limit parameter (the fourth parameter) set to 1, and replace the first occurrence.
    the second time, don't use a limit and it will delete the remaining Refrains
     
    yoavmatchulsky, Jan 27, 2009 IP