开发者

Regexp: Remove no alnum chars from a string

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开发者_StackOverflow string back:

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


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_-:=)§%&')


It seems you're forgetting delimiters:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜