且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否仅从字符串返回字母数字字符的函数?

更新时间:2023-02-26 12:47:54

警告:请注意,英语不仅限于A-Z.

尝试以删除除a-z,A-Z和0-9以外的所有内容:

Try this to remove everything except a-z, A-Z and 0-9:

$result = preg_replace("/[^a-zA-Z0-9]+/", "", $s);

如果字母数字的定义包括外语字母和过时的脚本,则您将需要使用Unicode字符类.

If your definition of alphanumeric includes letters in foreign languages and obsolete scripts then you will need to use the Unicode character classes.

尝试,仅保留A-Z:

$result = preg_replace("/[^A-Z]+/", "", $s);

发出警告的原因是,像résumé这样的单词包含字母é,该字母将与此不匹配.如果要匹配特定的字母列表,请调整正则表达式以包括这些字母.如果要匹配所有字母,请使用注释中提到的适当字符类.

The reason for the warning is that words like résumé contains the letter é that won't be matched by this. If you want to match a specific list of letters adjust the regular expression to include those letters. If you want to match all letters, use the appropriate character classes as mentioned in the comments.