将文本修剪为 340 个字符
我正在从数据库中提取博客文章。我想将文本的最大长度修剪为 340 个字符。
如果博客文章超过 340 个字符,我想将文本修剪到最后一个完整单词,并在末尾添加“...”。
E.g.
NOT: In the begin....
BUT: In the ...
I'm pulling blog posts from a DB. I want to trim the text to a max length of 340 characters.
If the blog post is over 340 characters I want to trim the text to the last full word and add '...' on the end.
E.g.
NOT: In the begin....
BUT: In the ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
似乎您希望首先将文本精确地修剪到 340 个字符,然后找到字符串中最后一个 ' ' 的位置并修剪到该数量。像这样:
It seems like you would want to first trim the text down to 340 characters exactly, then find the location of the last ' ' in the string and trim down to that amount. Like this:
其他答案向您展示了如何使文本大约 340 个字符。如果这适合您,请使用其他答案之一。
但是,如果您想要非常严格的最大 340 个字符,则其他答案将不起作用。您需要记住,添加
'...'
会增加字符串的长度,您需要考虑到这一点。另请注意,这里我使用了
strrpos
的重载,它采用偏移量来直接从字符串中的正确位置开始搜索,而不是首先缩短字符串。查看它在线运行:ideone
The other answers show you how you can make the text roughly 340 characters. If that's fine for you, then use one of the other answers.
But if you want a very strict maximum of 340 characters, the other answers won't work. You need to remember that adding the
'...'
can increase the length of the string and you need to take account of that.Note also that here I'm using the overload of
strrpos
that takes an offset to start searching directly from the correct location in the string, rather than first shortening the string.See it working online: ideone
如果您启用了 mbstring 扩展(现在大多数服务器上都有),您可以使用 mb_strimwidth 函数。
If you have the mbstring extension enabled (which is on most servers nowadays), you can use the mb_strimwidth function.
尝试:
try:
我把 John Conde 的答案放在一个方法中:
示例:
I put the answer of John Conde in a method:
Examples:
您可以尝试使用PHP自带的函数,例如wordwrap
you can try using functions that comes with PHP , such as wordwrap
functiontrim_characters( $text, $length = 340 ) {
}
使用此函数trim_characters() 将字符串修剪为指定数量的字符,并在空格处优雅地停止。
我认为这对你有帮助。
function trim_characters( $text, $length = 340 ) {
}
Use this function trim_characters() to trims a string of words to a specified number of characters, gracefully stopping at white spaces.
I think this is helpful to you.
为什么这样?
实际的正则表达式解决方案非常简单:
完整的方法PHP 可能如下所示:
更多说明:
$shownLength
是保持非常严格的限制(如 Mark Byers 提到的)\w\b
部分是为了避免末尾出现空格或标点符号(请参见下面的 1)在 ...< /code> 描述的如我所愿,我感觉
In the...
比较流畅(也不喜欢In the,...
等)Why this way?
Actual regex solution is very simple:
Full method in PHP could look like this:
More explanation:
$shownLength
is to keep very strict limit (like Mark Byers mentioned)\w\b
part is to avoid whitespace or interpunction at the end (see 1 below)In the ...
is described as desired, I feelIn the...
is more smooth (also don't likeIn the,...
etc.)最简单解决方案
多字节文本的
Simplest solution
For multi-byte text