This code will work correctly with your sample test.
A workaround is a token that replaces new lines before preg_match (which are restored after!) And the Ungreedy modifier at the end of regex (U)
<?php $token = '#####'; $text = <<<TXT This is a simple test text. Yet another line. START: This is the part that needs match. This part does not need capture. Wherever else text. TXT; $text = str_replace("\n", $token, $text); if (preg_match('/(?P<match>START:(.)*)(' . $token . '){1}[^ ]+/Uu', $text, $matches)) { $match = str_replace($token, "\n", $matches['match']); var_dump($match); } $text = str_replace($token, "\n", $text);
The output will be:
string(42) "START: This is the part that needs match."
source share