如何截断HTML到一定数量的字符? [英] How to truncate HTML to certain number of characters?

查看:136
本文介绍了如何截断HTML到一定数量的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些以某种博客格式显示的内容(有些来自外部来源,有些是特别编写的)。我想在一定数量的字符后切断文本,所以目前我正在这样做:

 <?= substr(strip_tags($ a ['content']),0,400)?> 

问题是,这会丢失所有的格式,而我只会得到一大块文本。但是,如果我不去掉标签,显然有些标签会被关闭并且会弄乱布局。

在X个字符之后截断的方法是什么,但也保留一些基本的格式? 解决方案

不相信如果这是你的问题的最佳方法,但它是一个简单一个,如果你只关心保留1或2个标签在html中保留一些基本格式,那么它就可以工作。

所以,你可以这样做:find要保留的标签,并用一些独特的字符组合替换它们,然后在截断字符串后,用您最初替换它们的标签查找/替换您创建的唯一字符串组合。

  $ content = str_replace(< br />,\\\
,$ a ['content']);
$ content = substr(strip_tags($ content),0,400);
echo str_replace(\\\
,< br />,$ content);


I have some content (some from an external source, some specially written) that is displayed in a kind of blog format. I want to cut off the text after a certain number of characters, so currently I'm doing this:

<?=substr( strip_tags($a['content']), 0, 400 )?>

The problem is, this loses all the formatting and I just get one massive blob of text. But if I don't strip the tags, obviously some tags will go unclosed and mess up the layout.

What would be a good way to truncate after X number of characters, but also keep some basic formatting?

解决方案

Not convinced if this is the best approach for your problem, but it is a simple one, and would work if you're only concerned about preserving 1 or 2 tags to retain some basic formatting in the html.

So, you could do something like: find the tags you want to keep and replace them with some unique combination of characters, then after truncating the string, find/replace the unique string combination you created with the tag you originally replaced them with.

$content = str_replace("<br/>", "\n", $a['content']);
$content = substr(strip_tags($content), 0, 400); 
echo str_replace("\n", "<br/>", $content);

这篇关于如何截断HTML到一定数量的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆