首页 > 解决方案 > 如何使用 PHP 获取以“abcd”开头的 html 标签?

问题描述

我有以下html代码:

    <div class="pictures">
       <figure>
           <img src="img/foo.jpg" height="400" width="400" id="abcd001"/>
           <figcaption>foo</figcaption> 
       </figure>
       <figure>
           <img src="img/bar.jpg" height="400" width="400" id="abcd002"/>
           <figcaption>bar</figcaption> 
       </figure>
       <figure>
           <img src="img/Joe.jpg" height="400" width="400" id="abcd003"/>
           <figcaption>Joe</figcaption> 
       </figure>
   </div>
   <div id="abcd004">
       Lorem Ipsum.
   <div>

并试图获取所有 html 标记及其 id 以“abcd”开头的孩子。XDOMDocument 类的查询功能似乎不适用于正则表达式。

$dom = new DomDocument();
$dom->load("/var/www/html/myWebsite.html")

$xpath = new DOMXPath($dom);
$xdom = $xpath->query("//img[@id='abcd*']");

foreach($xdom as $entry)
{
    echo $entry;
}

有什么建议么?

编辑: start-with 不起作用,因为该功能似乎不适用于 html 标签的 ID

标签: phphtml

解决方案


我认为您没有使用正确的语法start-with,请尝试以下操作:

$xpath = new DOMXPath($dom);
$xdom = $xpath->query("//img[starts-with(@id, 'abcd')]");


foreach($xdom as $entry) {
    echo $entry->getAttribute('src') . "\n";
}

在这里看到它的工作:https ://3v4l.org/04i5a


推荐阅读