PHP: How to tell if a string contains any special characters? [duplicate]

依然范特西╮ 提交于 2019-12-08 19:36:26

问题


I am using pspell to 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.

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)


回答1:


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
}



回答2:


If you just want to check whether the string $input consists only of characters a-z and A-Z you can use the following:

if(!preg_match('/^\[a-zA-Z]+$/',$input)) {
   // String contains not allowed characters ...
}


来源:https://stackoverflow.com/questions/3256175/php-how-to-tell-if-a-string-contains-any-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!