php - 将html标签添加到PHP中的字符串
问题描述
我想将 html 标签添加到 PHP 中的 HTML 字符串中,例如:
<h2><b>Hello World</b></h2>
<p>First</p>
Second
<p>Third</p>
第二个没有被任何 html 元素包裹,所以系统会在其中添加 p 标签,预期结果:
<h2><b>Hello World</b></h2>
<p>First</p>
<p>Second</p>
<p>Third</p>
尝试使用 PHP Simple HTML DOM Parser 但不知道如何处理它,这是我的想法示例:
function htmlParser($html)
{
foreach ($html->childNodes() as $node) {
if ($node->childNodes()) {
htmlParser($node);
}
// Ideally: add p tag to node innertext if it does not wrapped with any tag
}
return $html;
}
但是childNode不会循环进入Second,因为它里面没有包裹元素,并且不建议使用正则表达式来处理html标签,有什么想法吗?
非常感谢,谢谢。
解决方案
这是一个很酷的问题,因为它促进了对 DoM 的思考。
我提出了一个问题HTML Parsers 如何处理未标记的文本, @sideshowbarker对此进行了慷慨的评论,这让我思考,并提高了我对 DoM 的了解,尤其是关于文本节点的知识。
下面是一种基于 DoM 的查找候选文本节点并用“p”标签填充它们的方法。有很多文本节点我们应该不用管,比如我们用于格式化的空格、回车和换行(“丑陋”可能会去掉)。
<?php
$html = file_get_contents("nodeTest.html"); // read the test file
$dom = new domDocument; // a new dom object
$dom->loadHTML($html); // build the DoM
$bodyNodes = $dom->getElementsByTagName('body'); // returns DOMNodeList object
foreach($bodyNodes[0]->childNodes as $child) // assuming 1 <body> node
{
$text="";
// this tests for an untagged text node that has more than non-formatting characters
if ( ($child->nodeType == 3) && ( strlen( $text = trim($child->nodeValue)) > 0 ) )
{ // its a candidate for adding tags
$newText = "<p>".$text."</p>";
echo str_replace($text,$newText,$child->nodeValue);
}
else
{ // not a candidate for adding tags
echo $dom->saveHTML($child);
}
}
nodeTest.html 包含这个。
<!DOCTYPE HTML>
<html>
<body>
<h2><b>Hello World</b></h2>
<p>First</p>
Second
<p>Third</p>
fourth
<p>Third</p>
<!-- comment -->
</body>
</html>
输出是这样的......我没有费心回显外部标签。请注意,注释和格式已正确处理。
<h2><b>Hello World</b></h2>
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>fourth</p>
<p>Third</p>
<!-- comment -->
显然,如果您希望使事物更通用,则需要遍历 DoM 并在每个元素节点处重复搜索/替换。在此示例中,我们仅在Body节点处停止并处理每个直接子节点。
我不是 100% 确定代码是最有效的,如果我找到更好的方法,我可能会对此进行更多思考并更新。
推荐阅读
- javascript - 在一种方法中访问变量,在另一种方法中使用
- python - Python:水平翻转图像并重新排序目标
- php - 无法从数据库中获取数据 - Laravel
- c# - 配置保存未经授权的访问
- jquery - 如何使用 HTML 和 Jquery 根据文本修复文本区域高度
- algorithm - Big Theta Notation 公式令人困惑需要清晰
- node.js - 我在 chrome 中丢失了 Node.js 调试按钮
- wpf - 可以覆盖 DependencyProperties 吗?
- android - 带有 `wrap_content` 的 ConstraintLayout 高度
- dataset - BIRT 脚本数据源:未定义的变量