[英]file get contents + preg match
我尝试在div上返回数字,我想输入“ 01 55 33 44”
<div data-phone="01 55 33 44" class="agency_phone ">
Phone
</div>
我尝试一下:
$url = "myurl";
$raw = file_get_contents($url);
preg_match('/<div data-phone="(.*)"class="agency_phone "/isU',$raw,$output);
echo $output[1];
我没有回报,有人有想法吗?
提前致谢。
首先,您的regexp期望属性后的空格恰好为零,因此它不会与实际HTML的空格恰好匹配:
/<div data-phone="(.*)"class="agency_phone "
<div data-phone="01 55 33 44" class="agency_phone ">
无论如何,使用正则表达式从头开始编写一个体面的HTML解析器非常困难。 最简单的方法是DOM和XPATH,例如:
<?php
$html = '
<div data-phone="01 55 33 44" class="agency_phone ">
Phone
</div>
<p>Unrelated</p>
<div>Still unrealted</div>
<div data-phone="+34 947 854 712" class="agency_phone ">
Phone
</div>
';
$dom= new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$phones = $xpath->query('//div/@data-phone');
foreach ($phones as $phone) {
var_dump($phone->value);
}
string(11) "01 55 33 44"
string(15) "+34 947 854 712"
是缺少的空间吗?
[edit]将完整文件放在此处以进行复制[/ edit]
这有效:
// file url.html
<div data-phone="01 55 33 44" class="agency_phone ">
Phone
</div>
和:
<?php
// file test.php
$raw = file_get_contents('url.html');
preg_match('/data-phone="(.*)" class/',$raw,$output);
echo $output[1]; // 01 55 33 44
index.php
文件具有以下内容。
<?php
$url = "test.php";
echo $raw = file_get_contents($url);
preg_match('/data-phone="(.*)" class/', $raw, $output);
echo $output[1];
?>
以及其他带有html标记的文件source.php
。
<div data-phone="01 55 33 44" class="agency_phone ">
Phone
</div>
它将返回followig数组
Array
(
[0] => data-phone="01 55 33 44" class
[1] => 01 55 33 44
)
在本地主机上用html文件进行了测试,似乎可以正常工作。
<?php
$url = "myurl";
$subject = file_get_contents($url);
$pattern='<div data-phone="(.*)" class="agency_phone ">';
preg_match($pattern, $subject, $output);
echo $output[1];
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.