Shorten a text string in PHP

前端 未结 9 2370
暗喜
暗喜 2020-12-20 02:32

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:

$string = \"this is a string\";

9条回答
  •  失恋的感觉
    2020-12-20 03:29

    You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:

    function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
        //strip tags, if desired
        if ($strip_html) {
            $input = strip_tags($input);
        }
    
        //no need to trim, already shorter than trim length
        if (strlen($input) <= $length) {
            return $input;
        }
    
        //find last space within length
        $last_space = strrpos(substr($input, 0, $length), ' ');
        if($last_space !== false) {
            $trimmed_text = substr($input, 0, $last_space);
        } else {
            $trimmed_text = substr($input, 0, $length);
        }
        //add ellipses (...)
        if ($ellipses) {
            $trimmed_text .= '...';
        }
    
        return $trimmed_text;
    }
    

提交回复
热议问题