How to get first chars from a string, without cutting off the last word?

This PHP function will allow you to automatically get first n chars from a string, without cutting off the last word, this mean that you can extract text from a retrieved a mysql database (for example) without this cut comes in the middle of a word. This is useful if you want to display only the first words of a text (as an introduction for example).

$lg_max = 160; //Max authorized characters

//On vérifie si le texte est plus grand que le nombre de caractères spécifiés
if (strlen($chaine) > $lg_max)

//Si la réponse est non le script ne fait rien mais si c’est oui on continue…
{
$chaine = substr($chaine, 0, $lg_max);
//on cherche l’espace le plus proche du maximum des caractères autorisés (ici 160)
$last_space = strrpos($chaine, ” “);
//On ajoute … à la suite de cet espace
$chaine = substr($chaine, 0, $last_space).”…”;
}
echo $chaine;

Leave a Reply