2011-02-14 56 views
0

可以說我捕獲的網址爲$url = $_SERVER['REQUEST_URI'] or $_GET['q']檢查特定的文本的網址

如何檢查條件如果url包含一段文字說「x」?

什麼正則表達式將需要爲它

回答

2

如果你使用帶變量值的preg_match,確保你使用preg_quote來轉義任何特殊字符:

$look_for = "x"; 
if (preg_match("/".preg_quote($look_for, "/")."/i" , $url)) { 
    ... 
0

我覺得preg_match將使你:

if (preg_match("/x/i" , $url)) { 


} 
+1

afaik,strpos在這種情況下執行得更快 – JamesHalsall 2011-02-14 19:27:57

1

您還可以使用對strpos()函數

http://php.net/manual/en/function.strpos.php

這是一個例子:

$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"; 
}