4

I'm trying to run regular expression on the following string with PHP using preg_match_all function

"{{content 1}}{{content 2}}"

The result I'm looking for is array with 2 matches inside {{ and }}

Here is the expression '/\{\{(.+)\}\}/'

I'm suspecting that my expression is too greedy but how to make it less greedy?

marcin_koss
  • 5,763
  • 10
  • 46
  • 65

3 Answers3

4

You can use the ungreedy modifier ?, like so:

$regex = '/\{\{.*?\}\}/';

New regex will output:

Array
(
    [0] => Array
        (
            [0] => {{content 1}}
            [1] => {{content 2}}
        )

)

EDIT:

Just remembered another way to do this. You can just add a U (capital u) in the end of your regex string and result will be the same, like so:

$regex = '/\{\{.+\}\}/U';

Also, here is a useful list of regex modifiers.

marcio
  • 10,002
  • 11
  • 54
  • 83
1

You can also use the U PCRE modifier (Ungreedy)

Paulo H.
  • 1,228
  • 10
  • 15
-1

Is the regular expression string in a single quote or double quote PHP string? Because if it's in a double quoted string, curly braces include variables so need to be escaped twice.

"/\\{\\{(.+)\\}\\}/"
georgiecasey
  • 21,793
  • 11
  • 65
  • 74