如何检查URL是否包含某些单词?

问题描述 投票:2回答:3

如果当前网址包含某些字词,我想显示自定义内容。

到目前为止,如果URL只包含单词“cart”,我可以使用下面的代码实现此目的。但是,我希望能够检查“博客”,“活动”和“新闻”等其他词语。我该如何解决这个问题。

<?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 drupal-7
3个回答
3
投票

使用数组但使用preg_grep代替。对于这个用例,IMO是正确的preg_函数。

preg_grep - 返回与模式匹配的数组条目

 //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
)

Sandbox


1
投票

使用数组并循环通过它.. IE

<?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
    }      
}

0
投票

有几种解决方案,如preg_match_all()

Code

<?php $path = $_SERVER['REQUEST_URI'];
$find = '/(curt|blog|event|news)/i';
$number_of_words_in_my_path  = preg_match_all($find, $path);
if ($number_of_words_in_my_path > 0 && strstr($_SERVER['HTTP_REFERER'], 'path/to/site') !== false) : 
            ?>
  Custom content
<?php else: ?>
© www.soinside.com 2019 - 2024. All rights reserved.