Php 试图从网页中删除所有facebook链接
我正试图在页面上搜索Facebook的链接。但是,我得到一个空白页,没有任何错误消息 我的代码如下:Php 试图从网页中删除所有facebook链接,php,regex,Php,Regex,我正试图在页面上搜索Facebook的链接。但是,我得到一个空白页,没有任何错误消息 我的代码如下: <?php error_reporting(E_ALL); function getFacebook($html) { $matches = array(); if (preg_match('~^https?://(?:www\.)?facebook.com/(.+)/?$~', $html, $matches)) { print_r($matches)
<?php
error_reporting(E_ALL);
function getFacebook($html) {
$matches = array();
if (preg_match('~^https?://(?:www\.)?facebook.com/(.+)/?$~', $html, $matches)) {
print_r($matches);
}
}
$html = file_get_contents('http://curvywriter.info/contact-me/');
getFacebook($html);
一个更好的选择(更健壮)是使用DOMDocument和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\u match\u all
,并从您的模式中删除^
和$
。此外,请下次在您的问题中包含这些详细信息。你试过了什么,出了什么问题,你犯了什么错误,等等,这就是我得到-1的原因。请注意,我确实说过我没有得到任何输出。你能告诉我如何清理代码并删除额外的标记,如“taget=blank”和锚文本吗。我只想要facebook的网址。
<?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);