Regex, backreference problem in template with preg_match_all

I wonder what the problem with backreference is here:

preg_match_all('/__\((\'|")([^\1]+)\1/', "__('match this') . 'not this'", $matches);

a string is expected to match between __ (''), but it actually returns:

match this') . 'not this

any ideas?

+2
source share
4 answers

Make your regex uneven:

preg_match_all('/__((\'|")([^\1]+)\1/U', "__('match this') . 'not this'", $matches)
0
source

You cannot use backreference inside a character class, because a character class matches exactly one character, and a backlink can potentially match any number of characters or no one.

What you are trying to do requires a negative review, not a negative character class:

preg_match_all('/__\(([\'"])(?:(?!\1).)+\1\)/',
    "__('match this') . 'not this'", $matches);

- \'|" - - [\'"] - , , .


EDIT: , " " . . RegexBuddy.

abababdedfg,
^[a-g]+$ , ^(?:a|b|c|d|e|f|g)+$ 55 .

. abababdedfz,
^[a-g]+$ 21 ;
^(?:a|b|c|d|e|f|g)+$ 99 .

, . , , , . .

+5

, .

 /
   __
   (
       (\'|")
       ([^\1]+)
       \1
 /

[^\1] 1
. , , '1'.

:

/__\(('|").*?\1\).*/

, , :
/__\(('|")(.*?)\1\).*/

Edit: if the internal delimeter is not allowed, use the Qtax regex.
Because ('|").*?\1, although not greedy, it will still match all tethered trailers. In this case __('all'this'will"match'), and it is better to use ('[^']*'|"[^"]*) a

+2
source

You can use something like: /__\(("[^"]+"|'[^']+')\)/

+1
source

All Articles