开发者

PHP regex to search across multiple lines

开发者 https://www.devze.com 2022-12-31 04:06 出处:网络
I\'m using preg_* in PHP to search for the pattern <!-- %{data=THIS GETS MATCHED}% --> and pull out the matched text.

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 ca开发者_如何学Pythonn I edit my current pattern to have this search ability?


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

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


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

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


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
"
}
0

精彩评论

暂无评论...
验证码 换一张
取 消