首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP搜索远程网页中的字符串

问PHP搜索远程网页中的字符串
EN

Stack Overflow用户
提问于 2014-11-05 03:25:19
回答 2查看 1.5K关注 0票数 2

我正在尝试用PHP编写一个脚本,它将打开一个文本文件./urls.txt,并检查每个域中是否有特定的单词。我真的是PHP的新手。

示例:在以下域名中查找单词"Hello“。列表: Domain1.LTD Domain2.LTD Domain3.LTD

只需打印出域名+有效/无效即可。

代码语言:javascript
复制
<?PHP
$link = "http://yahoo.com"; //not sure how to loop to read each line from a file.
$linkcontents = file_get_contents($link);

$needle = "Hello";
if (strpos($linkcontents, $needle) == false) {
echo "Valid";
} else {
echo "Invalid";
}
?>
EN

回答 2

Stack Overflow用户

发布于 2014-11-05 03:36:54

代码语言:javascript
复制
$arrayOfLinks = array(
    "http://example.com/file.txt",
    "https://www.example-site-2.com/files/file.txt"
    );
    
    $needle = "Hello";
    
    foreach($arrayOfLinks as $link){ // loop through the array
    
        $linkcontents = file_get_contents($link);
    
        if (stripos($linkcontents , $needle) !== false) { // stripos is case-insensitive search
    // the needle exists in $linkcontents
    // !== false instead of != false since stripos can return 0 meaning the needle is the first word of the contents
        echo "Valid";
        } else {
    // the word does not exist in the given text
        echo "Invalid";
    }
}
票数 1
EN

Stack Overflow用户

发布于 2014-11-05 03:32:34

首先,出于安全性考虑,使用file_get_contents()时使用。

这将是一个正确的strpos示例:

代码语言:javascript
复制
//your previous code
if (strpos($linkcontents, $needle) !== false) { // see the !==
echo "Valid"; //Needle found
} else {
echo "Invalid"; //Needle not found
}

对于更复杂的爬行,您可以使用一些regexp而不是strpos。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26743350

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档