一個更好的選擇(更強大的)是使用DOM文檔和DOMXPath:
<?php
error_reporting(E_ALL);
function getFacebook($html) {
$dom = new DOMDocument;
@$dom->loadHTML($html);
$query = new DOMXPath($dom);
$result = $query->evaluate("(//a|//A)[contains(@href, 'facebook.com')]");
$return = array();
foreach ($result as $element) {
/** @var $element DOMElement */
$return[] = $element->getAttribute('href');
}
return $return;
}
$html = file_get_contents('http://curvywriter.info/contact-me/');
var_dump(getFacebook($html));
爲了您的具體問題,但是,我做了以下幾件事:
- 變化
preg_match
至preg_match_all
,以便在首次發現後不會停止。
- 刪除模式中的
^
(開始)和$
(結束)字符。您的鏈接將出現在文件的中間,而不是在開始或結束(絕對不是兩個!)
所以糾正代碼:
<?php
error_reporting(E_ALL);
function getFacebook($html) {
$matches = array();
if (preg_match_all('~https?://(?:www\.)?facebook.com/(.+)/?~', $html, $matches)) {
print_r($matches);
}
}
$html = file_get_contents('http://curvywriter.info/contact-me/');
getFacebook($html);
這有什麼錯呢? –
得到一個空白頁..沒有輸出.. –
這意味着你的比賽失敗。嘗試'preg_match_all',一次,並從你的模式中剔除'^'和'$'。 –