【问题标题】:check url for a specific piece of text检查特定文本的 url
【发布时间】:2011-02-14 19:21:12
【问题描述】:

假设我将 url 捕获为$url = $_SERVER['REQUEST_URI'] or $_GET['q']

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

需要什么正则表达式

【问题讨论】:

    标签: php html drupal


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你也可以使用 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";
      }
      

      【讨论】:

        【解决方案3】:

        除了查找字符串的函数之外,您可能还想查看 Drupal 的 arg() 函数:http://api.drupal.org/api/drupal/includes--path.inc/function/arg/6

        【讨论】:

        • 确实,这也是我的第一个想法
        【解决方案4】:

        我认为preg_match 会很好地为您服务:

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

        【讨论】:

        • afaik,strpos 在这种情况下执行得更快
        【解决方案5】:

        如果您使用来自野外的 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 模块有问题

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-07
          • 2021-12-26
          • 1970-01-01
          • 2016-07-27
          • 2017-07-18
          相关资源
          最近更新 更多