我正在使用PHP函数将文本拆分为最多N个字符的块。 一旦每个块以某种方式被“处理”,它就会再次连接起来。 问题是文本可以是HTML ...如果在打开的html标签之间发生拆分,则“处理”会被破坏。 有人可以提示只在封闭标签之间打破文本吗?
要求:
<body>
代码<HTML>
代码<head>
代码添加样本:(最大块长度= 173)
<div class="myclass">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dapibus sagittis lacus quis cursus.
</div>
<div class="anotherclass">
Nulla ligula felis, adipiscing ac varius et, sollicitudin eu lorem. Sed laoreet porttitor est, sit amet vestibulum massa pretium et. In interdum auctor nulla, ac elementum ligula aliquam eget
</div>
在上面的文字中,给定173个字符作为限制,文本会破坏@“adipiscing”,但这会破坏<div class="anotherclass">
。在这种情况下,拆分应在第一次关闭时进行,尽管比最大限制要短。
答案 0 :(得分:1)
“正确”的方法是解析HTML并在其文本节点上执行缩短操作。在PHP5中,您可以使用DOM extension,特别是DOMDocument::loadHTML()
。
答案 1 :(得分:0)
嗯,我已经使用了一个代码,我必须拆分由WYSIWYG输入的副本,并希望从中检索第一段。它的小狡猾,但为我做了伎俩。 如果你想添加show“n”,那么你可以使用substr将它添加到“intro”var中。 希望这能让你开始: - |
function break_html_description_to_chunks($description = null)
{
$firstParaEnd = strpos($description,"</p>");
$firstParaEnd += 4;
$intro = substr($description, 0, $firstParaEnd);
$body = substr($description, $firstParaEnd, strlen($description));
$temp = array("intro" => $intro, "body" => $body);
return $temp;
}