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