我正在嘗試通過URL搜索匹配的字符串,但下面的代碼片段似乎不起作用。如何將URL放入數組並在數組中搜索匹配的字符串?
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file = file($url);
if (in_array($search,$file)) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
我正在嘗試通過URL搜索匹配的字符串,但下面的代碼片段似乎不起作用。如何將URL放入數組並在數組中搜索匹配的字符串?
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file = file($url);
if (in_array($search,$file)) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
如果你只是搜索頁面上的字符串的發生,你可以使用
$str = file_get_contents($url);
if (strpos($str, $search) !== false) {
echo 'Success!';
} else {
echo 'Fail';
}
該代碼只能找到確切的$search
字符串(可能包括空格)的行。如果您解析HTML,請檢查PHP的DOMDocument類。或者,你可以使用正則表達式來提取你需要的東西。
由於@alex說,檢查allow_url_fopen已被激活。
您也可以使用strpos
搜索的字符串:
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file_content = file_get_contents($url);
if (strpos($file_content, $search) !== false) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
我怎麼會去通過$ str中的全部內容和循環計數的數量,例如? –
@Matt,你不需要循環,因爲整個頁面作爲字符串加載到'$ str'中。要計算另一個字符串中字符串的出現次數,請嘗試'substr_count()'(http://php.net/manual/en/function.substr-count.php)。 –
輝煌。謝謝。 –