是否仅从字符串返回字母数字字符的函数? [英] Function to return only alpha-numeric characters from string?

查看:36
本文介绍了是否仅从字符串返回字母数字字符的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个php函数,该函数将接受输入字符串并通过去除所有仅保留字母数字的特殊字符来返回其净化版本.

I'm looking for a php function that will take an input string and return a sanitized version of it by stripping away all special characters leaving only alpha-numeric.

我需要第二个功能相同但只返回字母A-Z的函数.

I need a second function that does the same but only returns alphabetic characters A-Z.

非常感谢任何帮助.

推荐答案

警告:请注意,英语不仅限于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.

这篇关于是否仅从字符串返回字母数字字符的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆