Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression in php: take the shortest match

Tags:

regex

php

I'm trying to do a PHP regular expression but i can't find the right way ...

Imagine I have this string: "hello, my {{name is Peter}} and {{I want to eat chocolate}}"

I want to take the parts between {{ and }}

But if I use preg_match("/\{\{(.*)?\}\}/", $string)

it returns me jut one string "{{name is Peter}} and {{I want to eat chocolate}}"

How can I tell to take the first coincidences of }} ?

Thank you

like image 908
FlamingMoe Avatar asked Feb 22 '11 14:02

FlamingMoe


People also ask

What is the purpose of preg_ match() regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.

What does preg_ match return?

Definition and Usage The preg_match() function returns whether a match was found in a string.

How to use regular expression in PHP?

PHP's Regexp POSIX Functions The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and false otherwise. The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.

How do I match a string in PHP?

The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().


2 Answers

Use

"/{{(.*?)}}/"

The expression ".*" is greedy, taking as many characters as possible. If you use ".*?" is takes as little characters as possible, that is it stops at the first set of closing brackets.

like image 135
Jens Avatar answered Sep 20 '22 15:09

Jens


The PCRE functions a greedy by default. That means, that the engine always tries to match as much characters as possible. The solution is simple: Just tell him to act non-greedy with the U modifier

/{{(.+)}}/U

http://php.net/reference.pcre.pattern.modifiers

like image 27
KingCrunch Avatar answered Sep 20 '22 15:09

KingCrunch