【问题标题】:Using 2 or more needles when using strpos [duplicate]使用 strpos 时使用 2 根或更多针 [重复]
【发布时间】:2013-03-25 00:36:12
【问题描述】:

我在 <a> 标签上运行 strpos 以查看它是否包含两个 url 之一。

目前我正在使用此波纹管 - 我将如何设置它来检查 - tumblr.com 或 google.com 是否存在?

function find_excluded_url ($url) {

    $find = "tumblr.com"; // OR GOOGLE.COM ....

    $pos = strpos($url, $find);

    if ($pos === false) {
        return false;
    } else {
        return true;
    }
}



// SET URL
   $url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";



// CALL FUNC
$run_url = find_excluded_url($url);

if ($run_url == true) {
    echo "URL - " . $url . "<br>";
}

【问题讨论】:

    标签: php strpos


    【解决方案1】:

    您不能在 strpos 中使用两根针。但是你可以做的是,使用它两次,用 or:

    function find_excluded_url ($url) {
      return (strpos($url, "tumblr.com")!==false) || (strpos($url, "google.com")!==false);
    }
    

    【讨论】:

      【解决方案2】:

      对于更复杂的搜索,您可能需要查看正则表达式。这会起作用:

      $subject = 'blablabgoogle
        balblabtumblrasd
        blaasdgoogleadsad';
      
      $pattern = '@(?:google\.com|tumblr\.com)@i';
      
      $result = preg_match($pattern, $subject, $subpattern, PREG_OFFSET_CAPTURE);
      
      if($result) echo 'Position: ' . $subpattern[0][1];
      

      这个性能(如果性能对您来说是个问题)取决于您有多少搜索查询以及您的干草堆有多大。正则表达式的开销相对较大,但是它们只需要遍历文本一次。如果你使用strpos 两次,那么长字符串会变得很昂贵。如果性能确实是一个问题,您还可以编写自己的 strpos,每个字符都对应一个字符。然而,我怀疑这是必要的。

      【讨论】:

        【解决方案3】:
        function find_excluded_url ($url, $searchURL) {
            $pos = strpos($url, $searchURL);
            if ($pos === false) {
                return false;
            } else {
                return true;
            }
        }
        
        // SET URL
           $url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";
        
        // CALL FUNC
        $run_url = find_excluded_url($url, 'google.com');
        if ($run_url == true)
            echo "URL - " . $url . "<br>";
        
        $run_url = find_excluded_url($url, 'tumblr.com');
        if ($run_url == true)
            echo "URL - " . $url . "<br>";
        

        【讨论】:

          猜你喜欢
          • 2011-10-17
          • 1970-01-01
          • 1970-01-01
          • 2017-02-11
          • 2018-05-19
          • 1970-01-01
          • 2016-03-31
          • 1970-01-01
          相关资源
          最近更新 更多