PHP 截断字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 截断字符串相关的知识,希望对你有一定的参考价值。

<?php

$string        = "Truncates a string at a certain position without cutting words into senseless pieces.";
$maxlength    = 75;
$extension    = " ...";

function truncate_string ($string, $maxlength, $extension) {

   // Set the replacement for the "string break" in the wordwrap function
   $cutmarker = "**cut_here**";

   // Checking if the given string is longer than $maxlength
   if (strlen($string) > $maxlength) {

       // Using wordwrap() to set the cutmarker
       // NOTE: wordwrap (PHP 4 >= 4.0.2, PHP 5)
       $string = wordwrap($string, $maxlength, $cutmarker);

       // Exploding the string at the cutmarker, set by wordwrap()
       $string = explode($cutmarker, $string);

       // Adding $extension to the first value of the array $string, returned by explode()
       $string = $string[0] . $extension;
   }

   // returning $string
   return $string;

}

// This Will output:
// "Truncates a string at a certain position without ?cutting? ..."
echo truncate_string ($string, $maxlength, $extension);

?>

以上是关于PHP 截断字符串的主要内容,如果未能解决你的问题,请参考以下文章

PHP 截断字符串

PHP:在分词处截断字符串

PHP 将字符串长度截断为n个字符并使用...

php 将帖子摘录截断为固定数量的字符

php 将帖子摘录截断为固定数量的字符

php 将帖子摘录截断为固定数量的字符