温馨提示×

php substr截取后如何添加省略号

PHP
小樊
90
2024-06-18 17:57:51
栏目: 编程语言

你可以使用PHP的substr函数截取字符串,然后在字符串末尾添加省略号。以下是一个示例代码:

$text = "This is a long text that needs to be shortened.";
$length = 20;

if (strlen($text) > $length) {
    $shortened_text = substr($text, 0, $length) . "...";
} else {
    $shortened_text = $text;
}

echo $shortened_text;

在上面的示例中,我们首先判断原始文本的长度是否大于指定的长度。如果是,则使用substr函数截取指定长度的字符串,并在末尾添加省略号。如果不是,则保持原始文本不变。最后,输出截取后的文本。

0