PHP获取源代码并搜索Word

时间:2009-01-16 15:27:25

标签: php regex search

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

这是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

2 个答案:

答案 0 :(得分:7)

<?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;

?>

答案 1 :(得分:1)

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;
    }