preg_replace: bad regex == 'Unknown Modifier&#

2019-03-19 21:01发布

问题:

I'm making up fake email addresses and I just want to make sure they are in a valid email format so I'm trying to remove any character that is not in the set below:

$jusr['email'] = preg_replace('/[^a-zA-Z0-9.-_@]/g', '', $jusr['email']);

I haven't had any trouble on my windows machine, but on the linux dev server I get this error each time this code runs:

Warning: preg_replace() [function.preg-replace]: Unknown modifier 'g' in /var/www/vhosts/....

I think it's the regex string, but I can't pin it down. Little help? Thanks.

Clarification: I'm not trying to accommodate all valid email addresses (unnecessary for my purpose), I just need to figure out what's wrong with my preg_replace regex.

回答1:

g is not a valid modifier in PCRE (the regex implementation PHP uses) because it's simply not needed; preg_replace() will perform global replacements by default. You'll find the modifier in true Perl regex as well as JavaScript regex, but not in PCRE.

Just drop the g:

$jusr['email'] = preg_replace('/[^a-zA-Z0-9.-_@]/', '', $jusr['email']);


回答2:

You have an invalid PCRE modifier. Here is the list of valid PCRE modifiers:

http://us.php.net/manual/en/reference.pcre.pattern.modifiers.php

The g (global) modifier is on by default, so you don't need it.



回答3:

The problem is that g is not a valid PCRE modifier. Try looking at preg_match_all.



回答4:

In addition to /g, the inner part of your regexp doesn't seem to be valid either:

[^a-zA-Z0-9.-_@]

First, the "^" (which is start-of-input metachar) makes no sense inside [...] (unless you allow email adresses that contain "^"). Second, the dash should be escaped or put to the end of the group, otherwise it will be treated as range operator. And most important, your expression disallows a wide range of perfectly valid email addresses. Check some examples.