2013-01-01 173 views
0

在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';} 
+0

你能解释*“如果搜索字符串包含了所有的坏词” * ......我不明白。你在这之后真的是什么? –

+1

请浏览[PHP的字符串函数首先列表](http://php.net/ref.strings),它可能只包含您正在查找的内容,例如http://php.net/trim – hakre

+0

我的坏话是在一个数组中。 – Norman

回答

4
$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

谢谢,Hanky Panky。我绝对需要休息。 – Norman

2

如果你带的龙头和最后面的空间,长度会下降到0,你可以很容易地变成了$fetch布尔:

$fetch = (bool) strlen(trim($newString)); 

trimDocs

1

使用正则表达式也许......

if (preg_match('/[^A-Za-z0-9]+/', $strFromSearchBox)) 
{ 
    //is true that $strFromSearchBox contains letters and/or numbers 
} 
相关问题