RegEx Help

Discussion in 'PHP' started by astrazone, Jul 26, 2010.

  1. #1
    Trying to replace this tag in a post :

    
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, [tag]13231[/tag] sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
    
    PHP:
    I want to get 13231 and replace it with other text.
     
    astrazone, Jul 26, 2010 IP
  2. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #2
    Try this. untested

    $content = preg_replace('/\[tag\](.*)\[\/tag\]/','$something_else',$content);
    PHP:
    EDIT: opps I had an extra apostrophe, try it now.
     
    Last edited: Jul 26, 2010
    MyVodaFone, Jul 26, 2010 IP
  3. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You should consider making the quantifier non-greedy, if there was ever multiple [tag]'s in the content - it would only match once.

    Like this:
    
    <?php
        $string = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, [tag]13231[/tag] sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
        $replacement_text = 'other text';
        
        $string = preg_replace('#\[tag\](.*?)\[/tag\]#', $replacement_text, $string);
        echo $string;
    ?>
    
    PHP:
     
    Deacalion, Jul 26, 2010 IP
  4. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #4
    Does the OP not need to backslash the forward / in [/tag\] to [\/tag\] ?

    Just asking...
     
    MyVodaFone, Jul 26, 2010 IP
  5. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I use '#' as the delimiter instead of '/'. So it doesn't clash with the closing tag.
     
    Deacalion, Jul 26, 2010 IP
  6. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #6
    ah right, didn't know that, thanks :)
     
    MyVodaFone, Jul 26, 2010 IP
  7. astrazone

    astrazone Member

    Messages:
    358
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    33
    #7
    thank you very much for the quick fix.
     
    astrazone, Jul 26, 2010 IP