Matching a multiple lines pattern via PHP's preg_match()

后端 未结 6 863
轻奢々
轻奢々 2020-12-10 00:33

How can I match subject via a PHP preg_match() regular expression pattern in this HTML code:

      #i',$str,$matches);
// result is in $matches[1]

See it in action here.

For your interest, here is a list of different modifiers you can pass in to preg_* functions. Flags that may interest you are:

  • s ("dotall") : this one makes . match every character, including newlines. So, say your

    .....

    was spread over multiple lines. Then you'd have to do

    preg_match('#
#is',$str,$matches);

in order to have the .* go over multiple lines (see the extra s at the end of the regex?).

  • m ("multiline") : this one just lets ^ and $ match start/end of line instead of just the start/end of string. You only really need it if you're using ^ and $ in your pattern and want them to match the start/end of each individual line in your input.
  • 提交回复
    热议问题
    6条回答
    •  孤街浪徒
      2020-12-10 01:19

      If you're looking for (e.g.) a h2 tag nested within a td tag where there's only whitespace in between the two, just use \s which includes spaces, newlines, etc. eg::

      preg_match('#
    \s*

    (.*?)

    \s*
    \s*

    (.*?)

    \s*