【发布时间】:2011-02-14 19:21:12
【问题描述】:
假设我将 url 捕获为$url = $_SERVER['REQUEST_URI'] or $_GET['q']。
如果 url 包含一段文字“x”,我如何检查条件?
需要什么正则表达式
【问题讨论】:
假设我将 url 捕获为$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) ) {
...
【讨论】:
你也可以使用 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
【讨论】:
我认为preg_match 会很好地为您服务:
if (preg_match( "/x/i" , $url) ) {
}
【讨论】:
如果您使用来自野外的 url,您可能想要使用 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 模块有问题
【讨论】: