tags:

views:

32

answers:

2

Hello,

how could I remove all characters from a string that aren't a-z/A-Z and 0-9 and _ with PHP? I tried that but it has no effect, it returns the same string back:

preg_replace('[^a-zA-Z0-9_]', '', 'Testdo123_-:=)§%&');
+1  A: 

It seems you're forgetting delimiters:

preg_replace('/\W+/', '', 'Testdo123_-:=)§%&');

\W stands for [^a-zA-Z0-9_]

SilentGhost
`\W` means all characters that are **not** word characters (maybe you should add an explanation).
Felix Kling
@Tim: he doesn't use delimiters, I'd guess
SilentGhost
Note that `\w` and its complement `\W` depend on the locale that is used.
Gumbo
+3  A: 

The preg_ prefixed functions require PCRE styled regular expression that use delimiters to separate the regular expression from optional flags/modifiers.

But you forgot delimiters. Or, to be precise: PHP takes the [ and ] as delimiters, leaving just ^a-zA-Z0-9_ as your actual regular expression.

So try this (using / as delimiters):

preg_replace('/[^a-zA-Z0-9_]/', '', 'Testdo123_-:=)§%&')
Gumbo