如何在PHP中获得字符串的前n个字符?什么是最快的方法来修剪一个字符串到特定的字符数,并添加'…如果需要的话?
当前回答
如果对截断字符串的长度没有硬性要求,可以使用这个来截断并防止截断最后一个单词:
$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";
// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);
// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));
// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));
在本例中,$preview将是“Knowledge is a natural right of every human”。
动态代码示例: http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713
其他回答
//The simple version for 10 Characters from the beginning of the string
$string = substr($string,0,10).'...';
更新:
基于检查长度的建议(也确保修剪和未修剪的字符串长度相似):
$string = (strlen($string) > 13) ? substr($string,0,10).'...' : $string;
所以你会得到一个最多13个字符的字符串;13个(或更少)普通字符或10个字符后跟“…”
更新2:
或作为函数:
function truncate($string, $length, $dots = "...") {
return (strlen($string) > $length) ? substr($string, 0, $length - strlen($dots)) . $dots : $string;
}
更新3:
我写这个答案已经有一段时间了,实际上我不再使用这段代码了。我更喜欢这个函数,它可以防止使用wordwrap函数打断单词中间的字符串:
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;
}
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
这就是我的工作
function cutat($num, $tt){
if (mb_strlen($tt)>$num){
$tt=mb_substr($tt,0,$num-2).'...';
}
return $tt;
}
其中$num表示字符数,$tt表示字符串,用于操作。
如果需要控制字符串字符集,多字节扩展可以派上用场。
$charset = 'UTF-8';
$length = 10;
$string = 'Hai to yoo! I like yoo soo!';
if(mb_strlen($string, $charset) > $length) {
$string = mb_substr($string, 0, $length - 3, $charset) . '...';
}
我为此开发了一个函数
function str_short($string,$limit)
{
$len=strlen($string);
if($len>$limit)
{
$to_sub=$len-$limit;
$crop_temp=substr($string,0,-$to_sub);
return $crop_len=$crop_temp."...";
}
else
{
return $string;
}
}
你只需要调用带有string和limit的函数 例如:str_short(“hahahahahah”,5); 它会剪掉你的绳子,并在最后加上“…” :)
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 格式化字节到千字节,兆字节,千兆字节
- 我可以将c#字符串值转换为转义字符串文字吗?
- 如何在PHP中获得变量名作为字符串?
- 在c#中解析字符串为日期时间
- 字符串中的单词大写
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到