tags:

views:

51

answers:

2

Valid characters include the alphabet (abcd..), numbers (0123456789), spaces, ' and ".

I need to strip any other characters than these from a string in PHP.

Thanks :)

+6  A: 

You can do this:

$str = preg_replace('/[^a-z0-9 "\']/', '', $str);

Here the character class [^a-z0-9 "'] will match any character except the listed ones (note the inverting ^ at the begin of the character class) that are then replaced by an empty string.

Gumbo
Don't you need the regex to be: `/[^a-z0-9 "\']/g` to match ALL occurrences of these characters? (as opposed to only the first one)
Razor Storm
RazorStorm, you're mixing up preg_replace with preg_match and preg_match_all. See: http://www.php.net/manual/en/function.preg-replace.php --"The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit)."
rubber boots
Oh I see, haha been doing too much perl lately. :P
Razor Storm
A: 

Gumbo's answer is correct for your given specification. But if your "specification" is only "symbolic", what you eventually need might be like the following:

$str = preg_replace('{ [^ \w \s \' " ] }x', '', $str );

[^ ] : negated character class (all except these inside)

\w : alphanumeric (letters and digits)

\s : white space

\' : '

Regards

rbo

rubber boots