如何在PHP中删除一定数量的字符后切断文本?

jie*_*exi 18 php string strip

我有两个字符串,我想限制为例如前25个字符.有没有办法在第25个字符后切断文本并在字符串末尾添加...?

所以'12345678901234567890abcdefg'会变成'12345678901234567890abcde ...'其中'fg'被切断.

Tyl*_*ter 44

我可以修改pallan的代码吗?

$truncated = (strlen($string) > 20) ? substr($string, 0, 20) . '...' : $string;
Run Code Online (Sandbox Code Playgroud)

如果它更短,则不会添加'...'.

  • 我知道这个答案已经有 7 年历史了,但是所有正在寻找这个问题答案的人都需要注意,如果您使用 utf8 编码,则需要将 strlen 函数替换为 mb_strlen 并将 substr 函数替换为 mb_substr (2认同)

Pas*_*TIN 10

为了避免在单词中间切换,您可能想要尝试该wordwrap功能; 我认为,这样的事情可以做到:

$str = "this is a long string that should be cut in the middle of the first 'that'";
$wrapped = wordwrap($str, 25);
var_dump($wrapped);

$lines = explode("\n", $wrapped);
var_dump($lines);

$new_str = $lines[0] . '...';
var_dump($new_str);
Run Code Online (Sandbox Code Playgroud)

$wrapped 将包含:

string 'this is a long string
that should be cut in the
middle of the first
'that'' (length=74)
Run Code Online (Sandbox Code Playgroud)

$lines阵列会像:

array
  0 => string 'this is a long string' (length=21)
  1 => string 'that should be cut in the' (length=25)
  2 => string 'middle of the first' (length=19)
  3 => string ''that'' (length=6)
Run Code Online (Sandbox Code Playgroud)

最后,你的$new_string:

string 'this is a long string' (length=21)
Run Code Online (Sandbox Code Playgroud)


使用substr,如下所示:

var_dump(substr($str, 0, 25) . '...');
Run Code Online (Sandbox Code Playgroud)

你得到了:

string 'this is a long string tha...' (length=28)
Run Code Online (Sandbox Code Playgroud)

哪个看起来不那么好:-(


还是,玩得开心!


Pee*_*lan 8

真的很快,

$truncated = substr('12345678901234567890abcdefg', 0, 20) . '...'
Run Code Online (Sandbox Code Playgroud)


Arn*_*rne 7

这个很短,并考虑到字边界,它不使用循环,这使得它非常有效

function truncate($str, $chars, $end = '...') {
    if (strlen($str) <= $chars) return $str;
    $new = substr($str, 0, $chars + 1);
    return substr($new, 0, strrpos($new, ' ')) . $end;
}
Run Code Online (Sandbox Code Playgroud)

用法:

truncate('My string', 5); //returns: My...
Run Code Online (Sandbox Code Playgroud)


edu*_*ves 5

http://php.net/manual/en/function.mb-strimwidth.php (PHP 4 >= 4.0.6, PHP 5, PHP 7)

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
echo "<br />";
echo mb_strimwidth("Hello", 0, 10, "...");
?>
Run Code Online (Sandbox Code Playgroud)

输出:

Hello W...
Hello
Run Code Online (Sandbox Code Playgroud)