【发布时间】:2021-05-27 17:50:57
【问题描述】:
我要将每个 HTML 标记拆分为一个新行。 这是我的来源:
<p><a href="http://www.example.com">Example Link</a></p>
<div class="text-center"><a href="http://www.example2.com">Example2 Link</a></div>
我会这样:
<p>
<a href="http://www.example.com">Example Link</a>
</p>
<div class="text-center">
<a href="http://www.example2.com">Example2 Link</a>
</div>
或者像这样:
<p>
<a href="http://www.example.com">
Example Link
</a>
</p>
<div class="text-center">
<a href="http://www.example2.com">
Example2 Link
</a>
</div>
这就是我所做的:
$myfile = fopen("html.txt", "r");
for ($i = 0; $i < 1; $i++) {
$line = fgets($myfile);
var_dump(preg_split('/(>)/', $line, 0, PREG_SPLIT_DELIM_CAPTURE));
}
这是将每个“>”放在单独的行(数组成员)中的输出。
array(9) {
[0]=>
string(2) "<p"
[1]=>
string(1) ">"
[2]=>
string(32) "<a href="http://www.example.com""
[3]=>
string(1) ">"
[4]=>
string(15) "Example Link</a"
[5]=>
string(1) ">"
[6]=>
string(3) "</p"
[7]=>
string(1) ">"
[8]=>
string(2) "
"
}
【问题讨论】:
-
使用DOMDocument 可能是最好的。您可以解析整个文档并递归循环遍历它,同时每行回显每个节点。
标签: php regex html-parsing