【问题标题】:PHP Get Source and Search for WordPHP 获取源代码并搜索 Word
【发布时间】:2009-01-16 15:27:24
【问题描述】:

我需要帮助我想编写一个在源代码中搜索单词的程序。

这里是一个 Python 示例:

import urllib2, re

site = "http://stackoverflow.com/"
tosearch = "Questions"
source = urllib2.urlopen(site).read()
if re.search(tosearch,source):
     print "Found The Word", tosearch

【问题讨论】:

    标签: php regex search


    【解决方案1】:
    <?php
    
    $site = "http://stackoverflow.com/";
    $tosearch = "Questions";
    $source = file_get_contents($site);
    if(preg_match("/{$tosearch}/", $source)): // fixed, thanks meouw
      echo "Found the the word {$tosearch}";
    endif;
    
    ?>
    

    【讨论】:

    • 其实 preg_match('/'.preg_quote($tosearch, '/').'/', $source) ... 或者在这种情况下只是: is_int(strstr($source, $搜索))
    • @troelskn 在这种情况下,我会使用 strpos($source, $tosearch) !== false
    • 你说得对......我把它们搞混了——这就是我在之前评论的最后部分要说的意思
    【解决方案2】:

    CURL 是个好方法:

        $toSearch = 'Questions';
    
        // create curl resource
        $ch = curl_init();
    
        // set url
        curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com/");
    
        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        // $output contains the output string
        $output = curl_exec($ch);
    
        // close curl resource to free up system resources
        curl_close($ch);
    
        //search for the string
        if(strpos($output, $toSearch ) !== FALSE ) {
           echo "Found The Word " . $toSearch;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-05
      • 2011-01-21
      相关资源
      最近更新 更多