Friday, June 8, 2018

How to trim text without cutting words

h1. By character count
<?php


function gen_string($string,$max)

{

$tok=strtok($string,' ');

$string='';

while($tok!==false && strlen($string)<$max)

 {

 if (strlen($string)+strlen($tok)<=$max) $string.=$tok.' '; else break;

 $tok=strtok(' ');

 }

return trim($string).'...';

}


$test = gen_string('This is a test string for testing.',10);

echo $test;


?>

h1. By word count
function shorten_string($string, $wordsreturned)

{

    $retval = $string;  //  Just in case of a problem

    $array = explode(" ", $string);

    /*  Already short enough, return the whole thing*/

    if (count($array)<=$wordsreturned)

    {

        $retval = $string;

    }

    /*  Need to chop of some words*/

    else

    {

        array_splice($array, $wordsreturned);

        $retval = implode(" ", $array)." ...";

    }

    return $retval;

}

No comments:

Post a Comment