【问题标题】:file get contents + preg match文件获取内容+预匹配
【发布时间】:2016-06-14 10:39:22
【问题描述】:

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

我没有回报, 有人有想法吗?

提前致谢。

【问题讨论】:

  • 请详细说明您的代码和问题以便更好地理解。
  • 我尽力了,只是想找回电话号码。
  • data-phone="([^"]+)" class
  • 但是使用dom解析器做任务是正确的

标签: php html class file-get-contents


【解决方案1】:

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 中微小的格式更改(想象一下它们交换 data-phoneclass 或在其间插入另一个属性)。当然,在极端情况下它们总是会失败。
【解决方案2】:

首先,您的正则表达式期望属性后正好有 0 个空格,因此它不会与您的实际 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"

【讨论】:

  • @ÁlvaroGonzález 如果我想获得特定类别的数据电话,该怎么表达?
  • //div[@class="classname"]/@data-phone
  • 嗯,在 XPATH 中按类名过滤并不简单。毕竟它是一种在开发时考虑到 XML 而非 HTML 的语言。您可以查看Selecting a css class with xpath 以获得一些建议(接受的答案非常棒)。
  • @ÁlvaroGonzález 感谢您提供的信息,非常感谢
【解决方案3】:

是缺少的空间吗?

[编辑] 将完整文件放在这里以供复制 [/编辑]

这行得通:

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

【讨论】:

  • 感谢保罗的帮助,但没有回报,空白页。
  • 页面返回NULL
  • 我更新了示例以包含您自己测试所需的一切
【解决方案4】:

用本地主机上的 html 文件测试,似乎工作正常。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多