2016-06-14 69 views
0

我尝试在一个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]; 

我有没有回报, somone有一个想法?

在此先感谢。

+0

请详细说明你的代码和问题,为更好地理解。 –

+0

我尽我所能,只是我想检索电话号码。 – Jeed

+0

'data-phone =“([^”] +)“class' – splash58

回答

0

index.php文件有如下内容。

<?php 
    $url = "test.php"; 
    echo $raw = file_get_contents($url); 
    preg_match('/data-phone="(.*)" class/', $raw, $output); 
    echo $output[1]; 
?> 

等多种文件source.php具有HTML标签。

<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 
) 
+0

值得注意的是,基于正则表达式的解决方案通常需要维护以适应源HTML中的微小格式更改(只要想象它们交换数据-phone'和'class'或插入另一个属性之间)当然他们总是会在边缘情况下失败 –

0

这是缺失的空间吗?

[编辑]这里 放满文件的再生用 [/编辑]

这工作:

// 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 
+0

感谢您的帮助Paul,但没有返回,空白页面。 – Jeed

+0

在页面上返回NULL – Jeed

+0

我更新了示例以包含您需要测试的所有内容 – pauledenburg

0

与本地主机上的HTML文件测试,似乎很好地工作。

<?php 
$url = "myurl"; 
$subject = file_get_contents($url); 
$pattern='<div data-phone="(.*)" class="agency_phone ">'; 
preg_match($pattern, $subject, $output); 
echo $output[1];  
?> 
1

首先,你的正则表达式期望的是属性后零个空间,因此不会与一个空格您的实际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" 
+0

哇谢谢!作品像一个魅力! – Jeed

+0

@ÁlvaroGonzález如果我希望得到数据电话的具体类别? – SML

+0

// div [@ class =“classname”]/@ data-phone – splash58