更好的方式来写多个strpos调用

问题描述:

我做了一个简单的脚本,查找网站的所有传出<a>标签,并显示它们。更好的方式来写多个strpos调用

要做到这一点首先,我刮了地图,把这些URL到一个数组,然后遍历拼抢每一个单独找<a>标签的网址后,我再运行每个发现标签strpos()看看它有什么网址,我想忽略。

该脚本大约需要5分钟(500页的抓取)才能完成(本地运行),我想知道是否有更快的方法来处理针对排除参数的针/干草堆搜索。目前我使用

//SEES IF URL CONTAINS EXCLUDED PARAM 
function find_excluded_url ($match_url) { 
    return strpos($match_url, "mydomain.co.uk") || 
     strpos($match_url, "tumblr.com") || 
     strpos($match_url, "nofollow") || 
     strpos($match_url, "/archive") || 
     strpos($match_url, "page/2"); 
} 

以然后显示使用

if (find_excluded_url($element) == false) { 
    echo "<a href='$element->href'>" . $element->href . "</a>"; 
} 

结果IM是有一个更好的性能的方式来实现这一目标?

很抱歉,如果这是一个非常明显的问题,这是我用PHP建立了第一个真正的东西

刚一说明,strpos返回0如果元素是在字符串的开头和false如果元素不在字符串中。

对于PHP 0false是同一件事,这意味着您的脚本不会识别以关键字开头的链接。

所以我建议你改变你的脚本是:

function find_excluded_url ($match_url) { 
    return strpos($match_url, "mydomain.co.uk") !== false || 
     strpos($match_url, "tumblr.com") !== false || 
     strpos($match_url, "nofollow") !== false || 
     strpos($match_url, "/archive") !== false || 
     strpos($match_url, "page/2") !== false; 
} 
+0

香港专业教育学院刚刚更新了我的上述问题,说明如何IM调用函数,并已作为你写的函数的方式一样的效果? – sam 2013-04-10 11:37:12

+0

不要尝试将$ match_url设置为mydomain.co.uk并使用您的代码,如果您不添加“!== false”,该函数将不会将其识别为匹配项,这就是为什么我建议您将其添加到你的功能。然而,如果你关心的是速度,记得调用一个函数会给代码增加开销,所以我建议你在if中内置strpos,它会稍微快一点。 – 2013-04-11 12:44:10

如果你想检查1串是在另一个,你应该使用下列2之一: http://php.net/manual/en/function.stristr.php
http://php.net/manual/en/function.strstr.php

strpos警告:“此函数可能返回布尔值FALSE,但也可能返回一个非布尔值,其值为FALSE。请阅读布尔部分了解更多信息。使用===运算符来测试返回值这个功能“。

/** 
* Loops through the array to see if one 
* of the values is inside the $needle 
* 
* @param string $needle 
* @param array $haystack 
* @return bool 
*/ 
function strstr_array($needle, array $haystack) 
{ 
    foreach($haystack as $search) { 
    if(strstr($needle, $search)) { 
     return true; 
    } 
    } 
    return false; 
} 

$haystack = array('my-domain.com', 'sub.my-domain.com'); 
var_dump(strstr_array('test my-domain.com or something', $haystack)); 
+0

问题是关于性能。该手册清楚地说明了strstr:“如果您只想确定在干草堆内是否出现特定针,请使用速度更快,占用内存更少的函数strpos()。” – 2013-04-10 13:02:47

function find_excluded_url($match_url, $excludeList) 
{ 
    foreach($excludeList as $excluded) 
    { 
     if(stristr($match_url, $excluded) !== FALSE) 
     return TRUE; 
     else return FALSE; 
    } 
} 

$excludes = array(
         'mydomain.co.uk' 
        , 'tumblr.com' 
        , 'nofollow' 
        , '/archive' 
        , 'page/2' 
       ); 

$example1 = 'http://example.mydomain.co.uk/dir/'; 
$example2 = 'https://not.in/excludes'; 
var_dump(find_excluded_url($example1, $excludes)); 
var_dump(find_excluded_url($example2, $excludes)); 

// output from browser: bool(true) bool(false) 

试试这个

if (preg_match('/word/i', $str)) 
+1

请随时解释您的答案。 – 2016-01-15 00:47:38