Problems with this regex in php

I am trying to run a regex on the next line with PHP using the preg_match_all function

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

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

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

I suspect my expression is too greedy, but how to make it less greedy?

+4
source share
3 answers

Can you use the ungreedy modifier ? , eg:

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

A new regular expression will appear:

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

EDIT:

Just remembered another way to do this. You can simply add U (capital u) to the end of the regex line, and the result will be the same:

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

In addition, here is a useful list of regular expression modifiers .

+4
source

You can also use the U modifier PCRE (Ungreedy)

+1
source

Is the regex string a single string or a double string of a PHP string? Because if it's on a double-quoted string, curly braces include variables, so they need to be escaped twice.

 "/\\{\\{(.+)\\}\\}/" 
-1
source

Source: https://habr.com/ru/post/1384445/


All Articles