PHP:如何判断一个字符串是否包含任何特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3256175/
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
PHP: How to tell if a string contains any special characters?
提问by JD Isaacks
I am using pspellto spell check some words. However if the word is something like G3523B it clearly is not a misspelled word but pspell changes it to GB. I would like somehow to qualify a word as a word before trying to spell check it. Maybe checking to see if the string contains any numbers or special characters.
我正在使用pspell拼写检查一些单词。但是,如果该词类似于 G3523B,它显然不是拼写错误的词,而是 pspell 将其更改为 GB。在尝试拼写检查之前,我想以某种方式将一个单词限定为一个单词。也许检查字符串是否包含任何数字或特殊字符。
So what is the best way to check a string for special chars or digits?
那么检查字符串中是否有特殊字符或数字的最佳方法是什么?
(if someone has a better idea to achieve what I am after please share)
(如果有人有更好的想法来实现我的目标,请分享)
回答by Sarfraz
How about using a regex:
如何使用正则表达式:
if (preg_match('/[^a-zA-Z]+/', $your_string, $matches))
{
echo 'Oops some number or symbol encountered !!';
}
else
{
// Everything fine... carry on
}
回答by Javaguru
If you just want to check whether the string $input consists only of characters a-z and A-Z you can use the following:
如果您只想检查字符串 $input 是否仅包含字符 az 和 AZ 您可以使用以下命令:
if(!preg_match('/^\[a-zA-Z]+$/',$input)) {
// String contains not allowed characters ...
}

