Matheus Simon Matheus Simon - 11 months ago 70
PHP Question

REGEX - ignore new line characters

I came across this line of code:

preg_match_all("!boundary=(.*)$!mi", $content, $matches);

but for

Content-Type: multipart/alternative;

It returns


When it should return


(without the

Any ideas how to fix this?

PS.: It should also work for when
is not present, only

Answer Source

There are two options.

  1. Use lazy dot matching and add an optional \r:

    preg_match_all("!boundary=(.*?)\r?$!mi", $content, $matches);

See this PHP demo

  1. Use a [^\r\n] negated character class matching any char but \r and \n:

    preg_match_all("!boundary=([^\n\r]*)!mi", $content, $matches);

Or, a shorter version, using the \V shorthand character class matching any character that is not a vertical whitespace (not a linebreak char):

preg_match_all("!boundary=(\V*)!mi", $content, $matches);

See this or this PHP demo.

Note that the second approach is much more efficient.