我想寫一個正則表達式來匹配除了包含「domain.com/file/」的字符串以外的所有東西。正則表達式來檢查除字符串以外的所有東西
所以,如果我給了一個網址,我想確保它不包含「domain.com/file/」。
我知道這可能是超級簡單,但我是正則表達式的noob。
我想寫一個正則表達式來匹配除了包含「domain.com/file/」的字符串以外的所有東西。正則表達式來檢查除字符串以外的所有東西
所以,如果我給了一個網址,我想確保它不包含「domain.com/file/」。
我知道這可能是超級簡單,但我是正則表達式的noob。
只是使用!在正則表達式
$pattern = '#!domain\.com/file/#';
if(preg_match($pattern,$data)){
}
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";
}
使用不區分大小寫匹配的例子:
if (stristr($input, 'domain.com/file/') === false) {
// not found.
}
要還回答了regex問題:你可以使用一個(?!...)
negative assertion爲用途:
if (preg_match("~(?!.*domain.com/file/)~", $string))
如果將其與其他比較結合使用,這很有意義。所有本身否定preg_match
的結果會更明智。
這可以在'.htaccess'中使用RewriteRule,但是'!'在正則表達式中沒有任何意義。 – mario