如何在PHP中获得字符串的前n个字符?什么是最快的方法来修剪一个字符串到特定的字符数,并添加'…如果需要的话?


当前回答

$width = 10;

$a = preg_replace ("~^(.{{$width}})(.+)~", '\\1…', $a);

或者使用wordwrap

$a = preg_replace ("~^(.{1,${width}}\b)(.+)~", '\\1…', $a);

其他回答

//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) . "...";

从4.0.6版开始,PHP就内置了这个功能。去看医生。

echo mb_strimwidth('Hello World', 0, 10, '...');

// outputs Hello W...

注意trimmarker(上面的省略号)包含在截断的长度中。

如果对截断字符串的长度没有硬性要求,可以使用这个来截断并防止截断最后一个单词:

$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 string_length_cutoff($string, $limit, $subtext = '...')
{
    return (strlen($string) > $limit) ? substr($string, 0, ($limit-strlen(subtext))).$subtext : $string;
}

// example usage:
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26);

// or (for custom substitution text
echo string_length_cutoff('Michelle Lee Hammontree-Garcia', 26, '..');