Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the shortest rather than longest possible regex match with preg_match()

I have string similar to this one:

{{something1}} something2 {{something3}} something4

How can I match only "something1" using the preg_match() function?

I tried:

preg_match("/\{\{(.*)\}\}/si",$content,$matches);

but this matched too much, returning

something1}} something2 {{something3

I tried adding \b to the pattern, but didn't get what I want that way either.

Could you please help me with this?

like image 438
Narek Avatar asked May 05 '11 12:05

Narek


2 Answers

a full answer - if our $var is:

STARTT 
FIRST KKK
SECOND KKK

1) In case we use:

$var = preg_replace('/STARTT(.*)KKK/', 'REPLACED-STRING', $var);

it will change everything from the STARTT to last KKK and Result will be:

REPLACED-STRING

2) In case we use:

$var = preg_replace('/STARTT(.*?)KKK/', 'REPLACED-STRING', $var);

Result will be:

REPLACED-STRING 
SECOND KKK
like image 138
T.Todua Avatar answered Oct 19 '22 23:10

T.Todua


Use non greedy modifier ? :

preg_match("/\{\{(.*?)\}\}/si",$content,$matches);
             here --^
like image 39
Toto Avatar answered Oct 20 '22 00:10

Toto