8

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.

doub1ejack
  • 10,627
  • 20
  • 66
  • 125

4 Answers4

26

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']);
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
3

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.

qJake
  • 16,821
  • 17
  • 83
  • 135
3

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

3

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.

user187291
  • 53,363
  • 19
  • 95
  • 127
  • 4
    `[^...]` means anything that is not `[...]`. But good catch on the `.-_`. – BoltClock Oct 04 '11 at 19:55
  • Good eye, thanks. As for the fact that this disallows lots of valid email addresses, that's not a concern for me. In this case, it's just easier to supply a fake email that will never be used than correct the Joomla api. – doub1ejack Oct 04 '11 at 20:30