开发者

Regexp: Remove no alnum chars from a string

开发者 https://www.devze.com 2022-12-30 02:33 出处:网络
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:

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

精彩评论

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

关注公众号