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

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

  •  15-07-2023
  •  | 
  •  

Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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

preg_match("/\C*?<!--/", $string, $extract);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top