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