在php中,如何检查字符串是否没有字符
目前我喜欢下面,并将-
替换为' '
。但是如果一个搜索字符串包含了所有的坏词,它会给我留下' '
(3个空格)。长度仍然显示为3,它将被发送到sql处理器。任何方法来检查字符串是否没有字符或数字?
$fetch = false;
#$strFromSearchBox = 'Why-you-foo-bar-I-ought-to-tar-you';
$strFromSearchBox = 'foo-bar-tar';
if(strlen($strFromSearchBox) >=2)
{
$newString = str_replace($theseWords,'',$strFromSearchBox);
$newString = str_replace('-',' ',$newString);
if(strlen($newString)>=2)
{
$fetch = true;
echo $newString;
}
}
if($fetch){echo 'True';}else{echo 'False';}
$fetch = false;
#$strFromSearchBox = 'Why-you-foo-bar-I-ought-to-tar-you';
$strFromSearchBox = 'foo-bar-tar';
if(strlen($strFromSearchBox) >=2)
{
$newString = str_replace($theseWords,'',$strFromSearchBox);
$newString = str_replace('-',' ',$newString);
$newString=trim($newString); //This will make the string 0 length if all are spaces
if(strlen($newString)>=2)
{
$fetch = true;
echo $newString;
}
}
if($fetch){echo 'True';}else{echo 'False';}
如果您去掉前导和最后面的空格,长度将下降到0,您可以轻松地将其转换为$fetch
布尔值:
$fetch = (bool) strlen(trim($newString));
参见trim
Docs
使用正则表达式…
if (preg_match('/[^A-Za-z0-9]+/', $strFromSearchBox))
{
//is true that $strFromSearchBox contains letters and/or numbers
}