如何在PHP中获得字符串的前n个字符?什么是最快的方法来修剪一个字符串到特定的字符数,并添加'…如果需要的话?
当前回答
$width = 10;
$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);
或者使用wordwrap
$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);
其他回答
if(strlen($text) > 10)
$text = substr($text,0,10) . "...";
最好像这样抽象你的代码(注意限制是可选的,默认为10):
print limit($string);
function limit($var, $limit=10)
{
if ( strlen($var) > $limit )
{
return substr($string, 0, $limit) . '...';
}
else
{
return $var;
}
}
如果对截断字符串的长度没有硬性要求,可以使用这个来截断并防止截断最后一个单词:
$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
$yourString = "bla blaaa bla blllla bla bla";
$out = "";
if(strlen($yourString) > 22) {
while(strlen($yourString) > 22) {
$pos = strrpos($yourString, " ");
if($pos !== false && $pos <= 22) {
$out = substr($yourString,0,$pos);
break;
} else {
$yourString = substr($yourString,0,$pos);
continue;
}
}
} else {
$out = $yourString;
}
echo "Output String: ".$out;
有时候,你需要将字符串限制到最后一个完整的单词ie:你不希望最后一个单词被打断,而是终止于最后一个单词的第二个。
例如: 我们需要将“This is my String”限制为6个字符,但不是“This i…”,我们希望它是“This…”,即我们将跳过最后一个单词中的破碎字母。
唷,我不擅长解释,这是代码。
class Fun {
public function limit_text($text, $len) {
if (strlen($text) < $len) {
return $text;
}
$text_words = explode(' ', $text);
$out = null;
foreach ($text_words as $word) {
if ((strlen($word) > $len) && $out == null) {
return substr($word, 0, $len) . "...";
}
if ((strlen($out) + strlen($word)) > $len) {
return $out . "...";
}
$out.=" " . $word;
}
return $out;
}
}
推荐文章
- 如何实现一个好的脏话过滤器?
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 格式化字节到千字节,兆字节,千兆字节
- 我可以将c#字符串值转换为转义字符串文字吗?
- 如何在PHP中获得变量名作为字符串?
- 在c#中解析字符串为日期时间
- 字符串中的单词大写
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到