2

我有工作代码可以在单词的末尾截断文本,但我正在寻找句子的结尾,所以寻找一个 .(句号)(空格)而不仅仅是一个空格。我还需要保留文本的 html 格式,以便它们也可以是几个列表项。

截断单词的代码:

$description_excerpt = preg_replace('/\s+?(\S+)?$/', '', substr($description_excerpt, 0, 200));
echo $description_excerpt;

假设 $description_excerpt 等于:

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>

<ul>
    <li>One. </li>
    <li>two. </li>
</ul>
<p>More text... </p>

然后,当它通过截断器运行时,它将返回:

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>

<ul>
    <li>One</li>
<ul>
4

1 回答 1

0

缩短 HTML 文本并不是那么简单。当然希望有文本的实际长度,而不是带有 HTML 标记的文本。在您的示例中,25 个字符占据<p> <ul> <li>. 但是,让我们把它放在最后。

最好的解决方案是两阶段操作。查找'. '和 2:关闭标签。

$description_excerpt = preg_replace('/(\.)\s+[^\.]*$/', '\1', 
                                    substr($description_excerpt, 0, 200));

preg_match_all('/<(?P<close>\/)?(?P<tag>\w+)(?P<atr>[^>]*)>/', 
               $description_excerpt, $m, PREG_SET_ORDER);
print_r($m);

现在您只需要查看哪些标签需要关闭。array_shift我建议使用和排队array_unshift。(记住,不需要关闭的标签)

If you want to be closer to the exact length of the text, this first divide the text into sections: text and HTML tags. Then make sure that the more you can extend the content. If not, close the tags.

于 2013-06-14T19:01:31.270 回答