Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first possible match using preg match in php

Tags:

php

preg-match

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?

like image 527
Rajaraman Avatar asked Dec 12 '22 12:12

Rajaraman


2 Answers

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

like image 64
Thomas F Avatar answered Dec 28 '22 07:12

Thomas F


Try this way:

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

preg_match("/(\[\[test[^]]*\]\])/im", $str, $match);

print_r($match);
like image 21
lsouza Avatar answered Dec 28 '22 06:12

lsouza