【问题标题】:How to check if URL contains certain words?如何检查 URL 是否包含某些单词?
【发布时间】:2019-03-23 01:32:32
【问题描述】:

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

到目前为止,如果 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 regex drupal-7 preg-match-all preg-grep


    【解决方案1】:

    使用数组,但改用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

    【讨论】:

      【解决方案2】:

      使用数组并循环遍历它.. 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
          }      
      }
      

      【讨论】:

      • 感谢@Lawrence 的编辑。我对 ole 复制粘贴很着急!
      【解决方案3】:

      有preg_match_all()等几种解决方案:

      代码

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

      【讨论】:

        猜你喜欢
        • 2020-07-06
        • 1970-01-01
        • 2013-10-21
        • 1970-01-01
        • 1970-01-01
        • 2015-03-14
        • 2021-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多