问题描述
如何在 PHP 中获取字符串的前 n 个字符?将字符串修剪为特定数量的字符并在需要时附加..."的最快方法是什么?
How can I get the first n characters of a string in PHP? What's the fastest way to trim a string to a specific number of characters, and append '...' if needed?
推荐答案
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
更新:
基于检查长度的建议(并确保修剪和未修剪字符串的长度相似):
Based on suggestion for checking length (and also ensuring similar lengths on trimmed and untrimmed strings):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
所以你会得到一个最多 13 个字符的字符串;13 个(或更少)普通字符或 10 个字符后跟..."
So you will get a string of max 13 characters; either 13 (or less) normal characters or 10 characters followed by '...'
更新 2:
或者作为函数:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
更新 3:
我写这个答案已经有一段时间了,我实际上不再使用这段代码了.我更喜欢这个功能,它使用 wordwrap
函数防止在单词中间破坏字符串:
It's been a while since I wrote this answer and I don't actually use this code any more. I prefer this function which prevents breaking the string in the middle of a word using the wordwrap
function:
function truncate($string,$length=100,$append="…") {
$string = trim($string);
if(strlen($string) > $length) {
$string = wordwrap($string, $length);
$string = explode("\n", $string, 2);
$string = $string[0] . $append;
}
return $string;
}
这篇关于将字符串截断为字符串的前 n 个字符,如果删除了任何字符,则添加三个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!