tags:

views:

141

answers:

3

I'm using preg_* in PHP to search for the pattern <!-- %{data=THIS GETS MATCHED}% --> and pull out the matched text.

The pattern for this is:

preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#', ...)

What I would like it to do is search across multiple lines for the string. For example:

<!-- %{data=
THIS GETS
MATCHED AND
RETURNED
}% -->

How can I edit my current pattern to have this search ability?

+1  A: 

Does preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#s', ...) work?

I don't have PHP here at work atm so I can't test it...

Dan McGrath
I managed to get it working by using `/<!-- %{' . $knownString . '=\s*(.*?)}% -->/s`. I'm terrible at regex, however, so if you're looking at that thinking "...lol?". Please tell me xD
Gaz
Seems fine to me :)
Dan McGrath
+3  A: 

You should add "s" pattern modifier, without it dot matches any character except for newline:

preg_match('#<!-- %{' . $knownString . '\s*=\s*(.*?)}% -->#s', ...)
Alexander Konstantinov
I'd secure $knownString with preg_quote() before gluing it to the rest of the regexp.
Kamil Szot
+1  A: 

This seems to work:

<?php
    $testString = "<!-- %{data=
THIS GETS
MATCHED AND
RETURNED
}% -->";
    $knownString = "data";
    preg_match( "@<!-- %\\{" . $knownString . "\\s*=\\s*([^\\}]+)\\}% -->@", $testString, $match );
    var_dump( $match );
?>

Returned:

array(2) {
  [0]=>
  string(54) "<!-- %{data=
THIS GETS
MATCHED AND
RETURNED
}% -->"
  [1]=>
  string(34) "THIS GETS
MATCHED AND
RETURNED
"
}
Salman A
`m`, or multiline mode, changes the meaning of the `^` and `$` anchors, enabling them to match at line boundaries as well as at the beginning and end of the string. Your regex works because you changed the dot to `([^\\}]`; the `m` is irrelevant.
Alan Moore
You're right. I've modified the code.
Salman A