Skip to content

Instantly share code, notes, and snippets.

@maximevalette
Created August 9, 2012 14:31
Show Gist options
  • Save maximevalette/3304662 to your computer and use it in GitHub Desktop.
Save maximevalette/3304662 to your computer and use it in GitHub Desktop.
Couper une chaîne de caractère sans casser de mot
<?php
/**
* @param $string string Chaîne de caractères à couper
* @param $max_length int Longueur maximum de la chaîne de caractère coupée
* @return string
*/
function word_cut($string, $max_length) {
if (strlen($string) <= $max_length) return $string;
$string = mb_substr($string, 0, $max_length);
$pos = mb_strrpos($string, " ");
if ($pos === false) return mb_substr($string, 0, $max_length)."…";
return mb_substr($string, 0, $pos)."…";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment