user1825932
user1825932

Reputation: 51

Remove Text With Preg_Replace

I have some text like the following example:

Some Text Here
[code]Some link[/code]
Text
[code]Link[/code]
Other Text
[code]Another Link[/code]
Other Text1

I want to remove all the text above, under, and between the two code. Here's an example of the output I want:

[code]Some Link[/code]
[code]Link[/code]
[code]Another Link[/code]

I use preg_replace for removing text above the first Code, in this way:

$message = preg_replace('/(.*?)\[code/si','[code',$message, 1);

Can you help me to remove the other text, using preg_replace?

Upvotes: 0

Views: 488

Answers (3)

Benjamin Toueg
Benjamin Toueg

Reputation: 10867

Just to make the solution of @Andreev a little more simple :

$text = "
Some Text Here
[code]Some link[/code]
Text
[code]Link[/code]
Other Text
[code]Another Link[/code]
Other Text1
";

$keywords = preg_match_all('/(\[code\].*\[\/code\])/Usmi', $text, $res);
print(implode($res[0]));

You can test it here : http://phptester.net/index.php?lang=en

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Assuming you can never have [code] abc [code] def [/code] ghi [/code], try this:

do {
    $message = preg_replace("((?:\[code\].*?\[/code\])*).*?(?=\[code\]))is","$1",$message,-1,$c);
} while($c);

Upvotes: 0

hugronaphor
hugronaphor

Reputation: 985

You can do this way:

     preg_match_all('/(\[code\].*\[\/code\])/Usmi', $text, $res);
        $cnt = 0;
        foreach ($res as $val) {
          $cnt++;
          $message .= $val[$cnt] . "<br />";          
        }
     echo $message;

Upvotes: 1

Related Questions