2013-01-01 171 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 
} 
相關問題