在PHP中截断文本?

rea*_*lph 15 php truncate

我试图在PHP中截断一些文本,并且偶然发现了这种方法(http://theodin.co.uk/blog/development/truncate-text-in-php-the-easy-way.html)通过评论似乎是一个很容易实现的解决方案.问题是我不知道如何实现它:S.

有人会介意我指明如何实现这一目标吗?任何帮助将不胜感激.

提前致谢.

Kai*_*ing 55

显而易见的事情是阅读文档.

但是要帮助: substr($str, $start, $end);

$str 是你的文字

$start是开头的字符索引.在你的情况下,它可能是0,这意味着一开始.

$end是截断的地方.例如,假设您想以15个字符结尾.你会这样写:

<?php

$text = "long text that should be truncated";
echo substr($text, 0, 15);

?>
Run Code Online (Sandbox Code Playgroud)

你会得到这个:

long text that 
Run Code Online (Sandbox Code Playgroud)

说得通?

编辑

您提供的链接是一个函数,用于在将文本切割为所需长度后找到最后一个空白区域,这样您就不会在单词的中间切断.但是,它缺少一个重要的东西 - 传递给函数的所需长度,而不是总是假设你希望它是25个字符.所以这是更新版本:

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,您将此函数粘贴到functions.php文件中,并在您的页面中调用它:

$post = the_post();
echo truncate($post, 100);
Run Code Online (Sandbox Code Playgroud)

这会将你的帖子剁到最后一次出现的空格之前或等于100个字符.显然你可以传递任何数字而不是100.无论你需要什么.

  • php的mb_strimwidth函数与单个内置函数完全相同:`mb_strimwidth($ string,0,15,"...")` (6认同)

the*_*imp 6

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}
Run Code Online (Sandbox Code Playgroud)


Fre*_*lip 5

$text="abc1234567890";

// truncate to 4 chars

echo substr(str_pad($text,4),0,4);
Run Code Online (Sandbox Code Playgroud)

这避免了将 4 个字符的字符串截断为 10 个字符的问题..(即源小于所需的)