Help Needed with preg_replace

Discussion in 'PHP' started by dct, Oct 15, 2005.

  1. #1
    I'm trying to use preg_replace to replace the contents between 2 tags {code} and {/code}. Like this
    $lCode = preg_replace("/\[code\].*\[\/code\] /", "Changed", $aText);
    PHP:
    However if there are 2 or more sets of the tags it only does the replace between the first opening {code} and last closing {/code} but I want it to replace each {code} blah blah {/code} separately.

    Hope I've explained this in an understandable way, any help much appreciated.
     
    dct, Oct 15, 2005 IP
  2. dct

    dct Finder of cool gadgets

    Messages:
    3,132
    Likes Received:
    328
    Best Answers:
    0
    Trophy Points:
    230
    #2
    Had to do
    $lCode = preg_replace("/\[code\].*?\[\/code\]/", "Changed", $aText);
    PHP:
    That question mark cost me much hair and time.
     
    dct, Oct 15, 2005 IP
  3. johnt

    johnt Peon

    Messages:
    178
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You could also have told the expression to be ungreedy - by default the pattern will match the largest amount of text that it can, so it would grab the first instance of {code} and the last instance if {/code}, ignoring any {/code} entries between the two.
    To make a pattern ungreedy, use the U flag, so
    $lCode = preg_replace("/\[code\].*\[\/code\] /U", "Changed", $aText);
    PHP:
    Hope it helps for next time

    John
     
    johnt, Oct 16, 2005 IP
    dct likes this.
  4. dct

    dct Finder of cool gadgets

    Messages:
    3,132
    Likes Received:
    328
    Best Answers:
    0
    Trophy Points:
    230
    #4
    Thanks John, I didn't know there were flags like that
     
    dct, Oct 16, 2005 IP