php - 使用正则表达式从 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);
解决方案
只是为了跟进我的评论,使用正则表达式并不是特别安全或足够健壮来管理 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
推荐阅读
- video - videojs-transcript 的最新工作版本是什么?
- typo3 - 如何按 id 显示 tx_news 标签标题?
- database - BLE 堆栈 - GATT 与 ATT
- haskell - 查找并返回第一个包含 char 的字符串(Haskell)
- ruby - 如何使用 ruby 从另一个方法调用一个方法?
- javascript - 有没有办法使用 SvelteKit 加载函数进行动态查询?
- keycloak - 从任何来源(身份提供者或用户联合)添加用户时订阅事件
- laravel - 无法将视图或路由发布到我的项目目录中
- postgresql - 尽管在列上缺少选择权,但仍删除行
- python - python中的工作功能但是我的测试仍然失败?