How to get the first possible match using preg match in php

I have one line like this

var str = 'abcd [[test search string]] some text here ]]'; 

I tried like this

 * preg_match("/\[\[test.*\]\]/i",$str,$match); 

If I do this, I get the output as shown below

 [[test search string]] some text here ]] 

I want the first match to only look like

 [[test search string]] 

Is it possible?

+4
source share
2 answers

Try as follows:

 $str = "var str = 'abcd [[test search string]] some text here ]]';"; preg_match("/(\[\[test[^]]*\]\])/im", $str, $match); print_r($match); 
+2
source

Short answer: Yes you can. You need to use lazy quantifiers. Therefore, instead of

 preg_match("/[[test.*]]/i",$str,$match); 

use

 preg_match("/\[\[test.*?\]\]/i",$str,$match); 

so that the function stops in the first match. Note: if you want to match an alphabetic character [ or ] , you need to escape from them, for example: \[ or \] .

After a little reaserch on php.net, I found a template modifier U (PCRE_UNGREEDY) that sets the default value for the template as lazy as greedy.
So this means that

 preg_match("/\[\[test.*\]\]/iU",$str,$match); 

also suitable for this purpose. The modifier U will do everything * , + ? in the regular expression as few characters as possible. In addition, quantifiers that were jagged ( *? +? And ?? ) will now become greedy (match as many characters as possible).

+9
source

Source: https://habr.com/ru/post/1495980/


All Articles