检查特定的文本的网址

问题描述:

可以说我捕获的网址为$url = $_SERVER['REQUEST_URI'] or $_GET['q']检查特定的文本的网址

如何检查条件如果url包含一段文字说“x”?

什么正则表达式将需要为它

如果你使用带变量值的preg_match,确保你使用preg_quote来转义任何特殊字符:

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

我觉得preg_match将使你:

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


} 
+1

afaik,strpos在这种情况下执行得更快 – JamesHalsall 2011-02-14 19:27:57

您还可以使用对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"; 
} 

除了用于查找字符串的函数,你可能也想看看Drupal的ARG()函数:http://api.drupal.org/api/drupal/includes--path.inc/function/arg/6

+0

事实上,这也是我第一次想到 – jpstrikesback 2011-02-14 19:28:08

如果从野外网址工作,你可能需要使用PHP的parse_url() ,http://www.php.net/manual/en/function.parse-url.php,这将使它易于使用。如果它是一个drupal URL,你可能会想要使用Drupal的arg()函数,http://api.drupal.org/api/drupal/includes--path.inc/function/arg/6,但它可能与Pathauto模块有问题