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

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

  •  15-07-2023
  •  | 
  •  

سؤال

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 <!--.

هل كانت مفيدة؟

المحلول

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);

نصائح أخرى

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

preg_match("/\C*?<!--/", $string, $extract);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top