PHP 7.3 update - preg Compilation failed [duplicat

2019-09-19 15:52发布

问题:

This question already has an answer here:

  • preg_match(): Compilation failed: invalid range in character class at offset 4 answers

After upgrading to PHP 7.3 I get this error

What does it mean?

preg_replace(): Compilation failed: invalid range in character class at offset 5 /var/www/...(97) #0 [internal function]: {closure}(2, 'preg_replace():...', '/var/www/dyntes...', 97, Array) #1 /var/www/...(97): preg_replace('/[^\pL-\/,.\d \...', '', 'd

$str = preg_replace('/[^\pL'.$allow_chars.']/', '', $str);

回答1:

Just escape special char in $allow_chars using preg_quote:

$str = preg_replace('/[^\pL'.preg_quote($allow_chars).']/', '', $str);

According to comment (you cannot use preg_quote), here is another way to do the job:

If the hyphen is in first posisition in $allow_char, you can do:

$str = preg_replace('/[^'.preg_quote($allow_chars).'\pL]/', '', $str);

An hyphen in first position wihin character class doesn't need to be escaped.