2011-11-29 61 views
0

我想寫一個正則表達式來匹配除了包含「domain.com/file/」的字符串以外的所有東西。正則表達式來檢查除字符串以外的所有東西

所以,如果我給了一個網址,我想確保它不包含「domain.com/file/」。

我知道這可能是超級簡單,但我是正則表達式的noob。

回答

0

只是使用!在正則表達式

$pattern = '#!domain\.com/file/#'; 
if(preg_match($pattern,$data)){ 

} 
+0

這可以在'.htaccess'中使用RewriteRule,但是'!'在正則表達式中沒有任何意義。 – mario

4

NOT運算符可以使用strstr這不是正則表達式。它名字很差,但如果找不到字符串,它將返回false。請務必使用===而不是==,因爲字符串將具有真值。

你不需要正則表達式的力量,除非你的問題不夠具體。

在回顧了幾件事後,看起來strpos實際上比strstr更快。您必須使用此功能才能使用===而不是==。從PHP文檔的strpos

例子:

$mystring = 'abc'; 
$findme = 'a'; 
$pos = strpos($mystring, $findme); 

// Note our use of ===. Simply == would not work as expected 
// because the position of 'a' was the 0th (first) character. 
if ($pos === false) { 
    echo "The string '$findme' was not found in the string '$mystring'"; 
} else { 
    echo "The string '$findme' was found in the string '$mystring'"; 
    echo " and exists at position $pos"; 
} 
+2

+1適當時通過正則表達式對字符串進行操作 – nickb

+0

這是一種更好的方法,因爲它比正則表達式便宜。 –

+0

應該使用stristr而不是strstr來使其更安全。 – peterp

1

使用不區分大小寫匹配的例子:

if (stristr($input, 'domain.com/file/') === false) { 
    // not found. 
} 
0

要還回答了問題:你可以使用一個(?!...) negative assertion爲用途:

if (preg_match("~(?!.*domain.com/file/)~", $string)) 

如果將其與其他比較結合使用,這很有意義。所有本身否定preg_match的結果會更明智。

相關問題