Regular expression: Replacement question

Discussion in 'PHP' started by weilies, Feb 3, 2010.

  1. #1
    hi RE gurus,

    i have a string
    "before [hide] some secret words [/hide] after"

    how can i use preg_replace and return the two strings below

    1. "before
    -- reply to view content -- after"

    2. "before some secret words after"

    Thanks for guiding
     
    weilies, Feb 3, 2010 IP
  2. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #2
    <?php
    $string = <<<STRING
    before [hide] some secret words [/hide] after
    STRING;
    
    //outputs - "before -- reply to view content -- after"
    $string1 = preg_replace("@\[hide\](.*)\[/hide\]@", "-- reply to view content --", $string);
    
    //outputs - "before some secret words after"
    $string2 = preg_replace("@\[hide\]|\[/hide\]@", "", $string);
    
    ?>
    PHP:
     
    Last edited: Feb 3, 2010
    danx10, Feb 3, 2010 IP
  3. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I think on the string1 one he wants to get rid of the text between the faux tags and replace them with a constant string.
     
    SmallPotatoes, Feb 3, 2010 IP
  4. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #4
    @ SmallPotatoes

    Thanks, fixed - don't know whats wrong with me today, keep missing things.
     
    danx10, Feb 3, 2010 IP
  5. weilies

    weilies Peon

    Messages:
    453
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks, but this work for
    but not
    how can i get ride of "\n" or "<br>"?
     
    weilies, Feb 5, 2010 IP
  6. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #6
    Sure add the 's' modifier.

    <?php
    $string = <<<STRING
    'start hide topic [hide] somehid decontent
    
    [/hide] after
    STRING;
    
    //outputs - "before -- reply to view content -- after"
    $string1 = preg_replace("@\[hide\](.*)\[/hide\]@s", "-- reply to view content --", $string);
    
    //outputs - "before some secret words after"
    $string2 = preg_replace("@\[hide\]|\[/hide\]@s", "", $string);
    
    echo $string1;
    
    ?>
    PHP:
     
    danx10, Feb 6, 2010 IP