2017-10-06 188 views
-2

我試圖找到一個preg_match過濾只包含的字符串特殊字符如-PHP preg_match只有特殊字符

但是,字符串本身可以包含特殊字符,但不應該只是特殊字符。

任何想法如何做到這一點?

如果字符串只包含特殊字符,結果應該返回true。所以像

if(preg_match('//',$string)) echo $string; //I leave the pattern empty as this is the actual question. 
+1

請顯示預期的輸出和你現在得到的結果+代碼 –

+0

當我在尋找匹配模式時,無法幫助代碼。我知道如何在字符串中找到特殊字符,但我確實需要它來過濾只包含特殊字符的字符串,例如------ – blackswan

+0

請給出一些測試用例。輸入字符串和預期結果。 – Toto

回答

2

您需要匹配任何字母數字字符的字符串。

$one= "%^&"; 
$two = "asd%asd"; 


function notOnlySpecialChars($str) { 
    if (preg_match('/[A-Za-z0-9]/', $str)) { //Replaced _ with - 
     return true; 
    } else { 
     return false; 
    } 
} 
notOnlySpecialChars($one); //false 
notOnlySpecialChars($two); //true 
+0

謝謝!我太愚蠢了我猜:-) – blackswan