Php 如何检查URL是否包含某些单词?
如果当前URL包含某些单词,我想显示自定义内容 到目前为止,如果URL只包含单词“cart”,我可以使用下面的代码实现这一点。但是,我希望能够检查其他单词,如“blog”、“event”和“news”。我该怎么做呢Php 如何检查URL是否包含某些单词?,php,regex,drupal-7,preg-match-all,preg-grep,Php,Regex,Drupal 7,Preg Match All,Preg Grep,如果当前URL包含某些单词,我想显示自定义内容 到目前为止,如果URL只包含单词“cart”,我可以使用下面的代码实现这一点。但是,我希望能够检查其他单词,如“blog”、“event”和“news”。我该怎么做呢 <?php $path = $_SERVER['REQUEST_URI']; $find = 'cart'; $pos = strpos($path, $find); if ($pos !== false && strstr($_SERVER['HTTP_REF
<?php $path = $_SERVER['REQUEST_URI'];
$find = 'cart';
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) :
?>
Custom content
<?php else: ?>
自定义内容
使用数组并在其中循环。。即
<?php $path = $_SERVER['REQUEST_URI'];
$arr = array();
$arr[0] = 'cart';
$arr[1] = 'foo';
$arr[2] = 'bar';
foreach($arr as $find){
$pos = strpos($path, $find);
if ($pos !== false && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false){
echo "custom content";
break; // To exit the loop if custom content is found -- Prevents it showing twice or more
}
}
有几种解决方案,例如preg\u match\u all()
:
代码
自定义内容
使用数组,但改用preg\u grep
。在我看来,它是这个用例的正确的preg\uuz
函数
-返回与模式匹配的数组项
输出
Array
(
[1] => shopping cart
)
感谢@Lawrence的编辑。。我匆忙地用ole复制粘贴!
//www.example.com?foo[]=somewords&foo[]=shopping+cart
//for testing
$_GET['foo'] = ['somewords', 'shopping cart'];
$foo = empty($_GET['foo']) ? [] : $_GET['foo'];
$words = ['cart','foo','bar'];
$words = array_map(function($item){
return preg_quote($item,'/');
},$words);
$array = preg_grep('/\b('.implode('|', $words).')\b/', $foo);
print_r($array);
Array
(
[1] => shopping cart
)