Hello All,

I have been wrestling with a regex for a couple of hours now and I finally had to give in and ask for help.
The weird thing is that it works if there are no new lines in the text, it fails if there is a new line(s) present.

The code:

$matches = array();
$pattern = '~\[CUSTOM_TAG(.*?)\](.*?)\[/CUSTOM_TAG\]~';
preg_match_all($pattern, $html, $matches);
if (!empty($matches[0])){
foreach($matches[0] as $code){
$parameter = preg_replace($pattern, '$1', $code);
$content = preg_replace($pattern, '$2', $code);//get the content between the pattern
}//foreach($matches[0] as $code){
}else{
echo 'Match failed';
}//if (!empty($matches[0])){


So with that code in mind, if the $html variable (the text to be processed) is:

$html = '<h1>Hello, world!</h1><p style="color:#ff0000;">Some red text</p>';

A match is found. *


If the $html variable is:

$html = '<h1>Hello, world!</h1>
<p style="color:#ff0000;">Some red text</p>';

Match not found

Hopefully I'm just missing something simple in my regex.

Thanks in advance!
Twitch

    You need to use the m modifier on your pattern, to have the pattern be able to match across multiple lines.

      Derokorian;11041101 wrote:

      You need to use the m modifier on your pattern, to have the pattern be able to match across multiple lines.

      Close; it's actually the "s" modifier that is needed here.

      EDIT: And by "needed", I simply mean "most convenient", really; you could certainly do without it, but you'd have to realize that the "." doesn't match newline characters:

      $pattern = '~\[CUSTOM_TAG(.*?)\](.|[\r\n])*?\[/CUSTOM_TAG\]~';

      or, if that seemingly-misplaced '' looks goofy to you...

      $pattern = '~\[CUSTOM_TAG(.*?)\]((?:.|[\r\n])*?)\[/CUSTOM_TAG\]~';

      (Lather, rinse, repeat for the preceding "." if you want to account for newlines within the [] tags.)

        Thanks for the quick responses guys. Derokorian put me on the right track by providing that link. Then I simply put "s" at the end and it worked.

        $pattern = '~[CUSTOM_TAG(.?)](.?)[/CUSTOM_TAG]~s';

          Write a Reply...