Skip to content

Instantly share code, notes, and snippets.

@sursir
Last active June 13, 2019 13:21
Show Gist options
  • Save sursir/c0b63744fe53a0c5379e5cf0c04f0080 to your computer and use it in GitHub Desktop.
Save sursir/c0b63744fe53a0c5379e5cf0c04f0080 to your computer and use it in GitHub Desktop.
preg_match regex pcre multi line

referer: https://stackoverflow.com/a/8959000/9544663

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('#<td>\s*<h2>(.*?)</h2>\s*</td>#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 <h2>.....</h2> was spread over multiple lines. Then you'd have to do

    preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment