【问题标题】:Get specific html portion with regex string matching in php在php中使用正则表达式字符串匹配获取特定的html部分
【发布时间】:2016-04-09 18:58:16
【问题描述】:

我正在尝试使用正则表达式 preg_match_allclass 标签 匹配来获取特定的 HTML 代码部分,但它返回的是空数组。

这是我想从完整的 HTML

中获取的 html 部分
<div class="details">
    <div class="title">
        <a href="citation.cfm?id=2892225&CFID=598850954&CFTOKEN=15595705"   
        target="_self">Restrictification of function arguments</a>  
    </div>
</div>

我在哪里使用这个 regex

preg_match_all('~<div class=\'details\'>\s*(<div.*?</div>\s*)?(.*?)</div>~is', $html, $matches );

注意: $html 变量包含我要搜索的整个 html。

谢谢。

【问题讨论】:

  • 可能是因为你在\'details\'处使用了错误的引号(-> \"details\" or ["']details["'])
  • 输出应该是什么(在你的例子中)?
  • 第一次使用正则表达式,我认为它应该给出
    内的内容。我不知道它将如何返回输出。
  • 在“title” div 或“details” div 内?

标签: php regex


【解决方案1】:

您正在寻找正则表达式中的单引号,而不是 $html 中的双引号。

您的正则表达式应如下所示:

'~<div class="details">\s*(<div.*?</div>\s*)?(.*?)</div>~is'

或更好:

'~<div class=[\'"]details[\'"]>\s*(<div.*?</div>\s*)?(.*?)</div>~is'

【讨论】:

  • 感谢您的回答。我仍然得到空数组。我按照你说的使用: preg_match_all('~
    \s*(\s*)?(.*?)~is', $html, $matches );我做错了吗?
  • 我试过你展示的测试用例,$matches 不是空的。
  • 能否请您发布您正在尝试的完整代码? (或者我可以分享我的)
  • 请更新您的问题以显示更多代码,因为我没有做任何与您正在做的不同的事情(如现在所示)。
  • 您的代码正在运行。我正在使用正在删除标签的 html_entities 函数(是的,我对此很糟糕)。非常感谢
【解决方案2】:

最好使用DOM 方法!

<?php
$html = '<div class="details">
    <div class="title">
        <a href="citation.cfm?id=2892225&CFID=598850954&CFTOKEN=15595705"   
        target="_self">Restrictification of function arguments</a>  
    </div>
</div>';

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXpath($doc);
$divs = $xpath->query('//div[@class="title"]');
print_r($divs);
?>

【讨论】:

  • 这绝对是比使用正则表达式更好的方法。
  • 不确定打印 DOMNodeList 对象是否会给出尝试的结果。
  • 谢谢,但它对于我的课堂作业,我必须将它与正则表达式一起使用
  • @CasimiretHippolyte:肯定不会,只是为了确保找到任何元素。
猜你喜欢
相关资源
最近更新 更多
热门标签