preg replace help needed

Discussion in 'PHP' started by DarkAge, Dec 2, 2008.

  1. #1
    I'm trying to remove all bbcode tags in my forum post with the following:

    
    $patterns[0] = "/\[.+\]/i"; 
    $replacements[0] = ""; 
    $postText = preg_replace($patterns, $replacements, $postText); 
    
    Code (markup):
    However this also removes nested tags. Eg:
    'tag1 begin, tag2 begin, tag2 end, tag1 end' <-- this will get completely deleted.

    Instead it should have matched tag1 then tag2 then... and so on.

    Any input on what I can do to accomplish this without trying to match each individual tag?

    Thanks in advance.
     
    DarkAge, Dec 2, 2008 IP
  2. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #2
    Use ungreedy matching:
    "/\[.+?\]/i";
    Code (markup):
     
    wmtips, Dec 2, 2008 IP
  3. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #3
    Quick and dirty.
    '#\[[^\]]+\]#'
    Code (markup):
    A little less leanient
    '#\[/?[a-z0-9_ ]+\]#i'
    Code (markup):
    Also a quick note, if there's no alphabet characters (a-z) in your pattern, the "i" flag is absolutely useless. :)
     
    joebert, Dec 2, 2008 IP
  4. DarkAge

    DarkAge Active Member

    Messages:
    353
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #4
    thanks for the answers, ill try it out later tonight
     
    DarkAge, Dec 2, 2008 IP
  5. Mr.Shan0

    Mr.Shan0 Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Use this:

    "/\[(.*?)\]/i"
    Code (markup):
    it'll surely work :)
     
    Mr.Shan0, Dec 3, 2008 IP