首页 > 解决方案 > 使用正则表达式从 HTML 中提取标签属性

问题描述

我想读取带有单词标题的所有标签属性,下面的 HTML 示例

<html>
    <head>
        <title> </title>
    </head>
    <body>
        <div title="abc"> </div>
        <div> 
            <span title="abcd"> </span>
        </div>
        <input type="text" title="abcde">
    </body>
</html>

我试过这个正则表达式函数,它不起作用

preg_match('\btitle="\S*?"\b', $html, $matches);

标签: phpregex

解决方案


只是为了跟进我的评论,使用正则表达式并不是特别安全或足够健壮来管理 HTML(尽管有一些 HTML - 完全没有希望任何工作) - 阅读https://stackoverflow.com/a /1732454/1213708

使用 DOMDocument 提供了一种更可靠的方法,在您可以使用 XPath 并搜索任何title属性之后进行处理//@title@符号是属性的 XPath 表示法)。

$html = '<html>
<head>
   <title> </title>
</head>
 <body>
   <div title="abc"> </div>
   <div> 
           <span title="abcd"> </span>
   </div>
       <input type="text" title="abcde">
</body>
</html>';

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

$xpath = new DOMXPath($doc);

foreach($xpath->query('//@title') as $link) {
    echo $link->textContent.PHP_EOL;
}

哪个输出...

abc
abcd
abcde

推荐阅读