如何在 PHP 中截断一定数量的字符后的文本?
我有两个字符串,我想限制为前 25 个字符。 有没有办法在第 25 个字符之后截断文本并在字符串末尾添加 ... ?
所以'12345678901234567890abcdefg' 会变成“12345678901234567890abcde...”,其中“fg”被切断。
I have two string that i want to limit to lets say the first 25 characters for example. Is there a way to cut off text after the 25th character and add a ... to the end of the string?
So '12345678901234567890abcdefg'
would turn into '12345678901234567890abcde...' where 'fg' is cut off.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
我知道已经晚了,但如果其他人返回此页面,这样做就可以了,
I know its to late, but if anyone else is returning to this page, this will do,
substr 函数是适合您的函数
substr function is the right one for you
您正在寻找 substr 方法。
这将为您提供字符串的第一个卡盘,然后您可以将任何您想要的内容附加到末尾。
You're looking for the substr method.
This will get you the first chuck of the string and then you can append whatever you'd like to the end.
我会同意帕斯卡·马丁的答案,并进行一些额外的改进。 因为;
1 - “PHP wordwrap”,自动尊重单词边界
2 - 如果您的字符串包含超过 25 个字符的单词(啊,所以没有什么可做的),您可以强制“PHP wordwrap”剪切单词。(改进)
3 - 如果你的字符串短于25个字符,那么“...”在完整的句子后会显得很难看。(改进)
I would go with Pascal MARTIN's answer, with some additional improvements. Because;
1 - "PHP wordwrap", respects word boundaries automatically
2 - If your string contains a word more than 25 chars(aagh, so there is nothing to do) you can force "PHP wordwrap" to cut word.(improvement)
3 - If your string is shorter than 25 chars, then "..." will seem ugly after a complete sentence.(improvement)
http://fr.php.net/manual/en/function.substr。 php
http://fr.php.net/manual/en/function.substr.php
可以解决这个问题,但是如果你正在处理单词,你可能想要切断单词边界,这样你就不会有部分单词这样做:快速 bl...
所以要做到这一点(从我的顶部粗略地得出)头):
Would do the trick, but if you are dealing with words, you might want to cut off on word boundries so you don't have partial word doig this: The quick bl...
So to do that (crude off the top of my head):
为了避免在单词中间剪切,您可能需要尝试
wordwrap
功能 ; 我想,这样的事情可以做到:$wrapped
将包含:$lines
数组将类似于:最后,你的
$new_string
:使用 substr,像这样:
你会得到:
看起来不太好 :-(
不过,玩得开心!
To avoid cutting right in the middle of a word, you might want to try the
wordwrap
function ; something like this, I suppose, could do :$wrapped
will contain :The
$lines
array will be like :And, finally, your
$new_string
:With a substr, like this :
You'd have gotten :
Which doesn't look that nice :-(
Still, have fun !
这个很短并且考虑了字边界,它不使用循环,这使得它非常有效
用法:
This one is short and takes word boundary into account, it doesn't use loops which makes it very efficient
Usage:
http://php.net/manual/en/function.mb-strimwidth.php
(PHP 4 >= 4.0.6、PHP 5、PHP 7)
输出:
http://php.net/manual/en/function.mb-strimwidth.php
(PHP 4 >= 4.0.6, PHP 5, PHP 7)
output:
我可以修改pallan的代码吗?
如果“...”较短,则不会添加它。
May I make a modification to pallan's code?
This doesn't add the '...' if it is shorter.
真的很快,
Really quickly,