I have one string like this
var str = 'abcd [[test search string]] some text here ]]';
I have tried like this
* preg_match("/\[\[test.*\]\]/i",$str,$match);
If I execute this, I am getting the output like the below
[[test search string]] some text here ]]
I want the first match only like
[[test search string]]
Is it possible?
Short answer: Yes you can. You need to use lazy quantifiers. So instead of
preg_match("/[[test.*]]/i",$str,$match);
use
preg_match("/\[\[test.*?\]\]/i",$str,$match);
to make the function stop at the first match.
Note: if you want to match a literal [ or ]charactor you need to escape them like: \[ or \].
After a little reaserch on php.net I discovered a pattern modifier U (PCRE_UNGREEDY) that will set the default for the pattern to lazy as apposed to greedy.
So this means that
preg_match("/\[\[test.*\]\]/iU",$str,$match);
will also suit for this purpose. The U modifier will make all *, +, ? in the regex match as few characters as possible. Also, quantifiers that used to be ungreedy (*?, +?, and ??) will now become greedy (match as many characters as possible).
Try this way:
$str = "var str = 'abcd [[test search string]] some text here ]]';";
preg_match("/(\[\[test[^]]*\]\])/im", $str, $match);
print_r($match);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With