如何在PHP中获得字符串的前n个字符?什么是最快的方法来修剪一个字符串到特定的字符数,并添加'…如果需要的话?
当前回答
使用子串
http://php.net/manual/en/function.substr.php
$foo = substr("abcde",0, 3) . "...";
其他回答
最好像这样抽象你的代码(注意限制是可选的,默认为10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
Substr()是最好的,你还需要先检查字符串的长度
$str = 'someLongString';
$max = 7;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...';
}
Wordwrap不会修剪字符串,只是分割它…
我使用的函数是:
function cutAfter($string, $len = 30, $append = '...') {
return (strlen($string) > $len) ?
substr($string, 0, $len - strlen($append)) . $append :
$string;
}
看到它的行动。
如果对截断字符串的长度没有硬性要求,可以使用这个来截断并防止截断最后一个单词:
$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
这个函数可以在中间不中断单词的情况下完成工作
function str_trim($str,$char_no){
if(strlen($str)<=$char_no)
return $str;
else{
$all_words=explode(" ",$str);
$out_str='';
foreach ($all_words as $word) {
$temp_str=($out_str=='')?$word:$out_str.' '.$word;
if(strlen($temp_str)>$char_no-3)//-3 for 3 dots
return $out_str."...";
$out_str=$temp_str;
}
}
}
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- PHP中的echo, print和print_r有什么区别?
- 如何删除表中特定列的第一个字符?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 将整数转换为字符串,以逗号表示千
- 如何将XML转换成PHP数组?
- 将JavaScript字符串中的多个空格替换为单个空格
- 如何将对象转换为数组?
- printf()和puts()在C语言中的区别是什么?
- 从IP地址获取位置
- jQuery -替换字符串中某个字符的所有实例
- Base64长度计算?
- 使用split("|")按管道符号拆分Java字符串
- 获取数组值的键名