How to match everything (including new line) up to the first occurance of a substring?

StackOverflow https://stackoverflow.com/questions/23458969

  •  15-07-2023
  •  | 
  •  

Question

As the title states, how to match anything up to the first occurance of the substring <!--?

Here's my test:

$string = "-->Hello world\r\nI feel <!--good <!--again";
preg_match("/-->.*<!--/s", $string, $extract);
var_dump($extract);

The result is:

array (size=1)
 0 => string '-->Hello world
I feel <!--good <!--' (length=36)

Where I need it to stop after the first time it sees <!--.

Était-ce utile?

La solution

The simplest solution would be to make the quantifier lazy, telling it to match as few characters as possible (instead of as many as possible, as unadorned quantifiers do because they are greedy by default):

preg_match("/-->.*?<!--/s", $string, $extract);

Autres conseils

To complete Tim Pietzcker answer, there is an other way without the s modifier:

preg_match("/\C*?<!--/", $string, $extract);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top