0

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?

2
  • Have you tried using preg_split ? Jan 22, 2013 at 14:41
  • what's the usage of preg_split? Jan 22, 2013 at 14:50

3 Answers 3

1

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;
1
  • but i need to put the content of my text, back in my variable $message Jan 22, 2013 at 14:56
1

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

0

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);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.