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
The preg_match() function will tell you whether a string contains matches of a pattern.
Definition and Usage The preg_match() function returns whether a match was found in a string.
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.
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().
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.
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
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