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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5199133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:35:43  来源:igfitidea点击:

Function to return only alpha-numeric characters from string?

phpregex

提问by Scott B

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.

我正在寻找一个 php 函数,它将接受一个输入字符串并通过去除所有特殊字符只留下字母数字来返回它的清理版本。

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

我需要第二个功能相同但只返回字母字符 AZ 的函数。

Any help much appreciated.

非常感谢任何帮助。

回答by Mark Byers

Warning: Note that English is not restricted to just A-Z.

警告:请注意,英语不仅限于 AZ。

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

尝试这种去除除包括AZ,az和0-9的一切:

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

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

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

Try thisto leave only A-Z:

试试这个只留下 AZ:

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

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.

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

回答by Mark Baker

Rather than preg_replace, you could always use PHP's filter functionsusing the filter_var()function with FILTER_SANITIZE_STRING.

不是preg_replace,你总是可以使用PHP的过滤功能,使用filter_var()与功能FILTER_SANITIZE_STRING

回答by Sky7ure

  1. Santize for numbers [0-9] and alphabets in general [\pL]:
  1. Santize 数字 [ 0-9] 和一般字母 [ \pL]:
$string = preg_replace("/[^0-9\pL]+/", "", $string)
  1. Santize specifically for the alphabets A to Z (case-insensitive) [a-zA-Z]:
  1. Santize 专门针对字母 A 到 Z(不区分大小写)[ a-zA-Z]:
$string = preg_replace("/[^a-zA-Z]+/", "", $string)