Last active
December 29, 2015 13:10
-
-
Save waelio/58c2a7079a0846b789e1 to your computer and use it in GitHub Desktop.
limiting string length by number of charachters while preserving whole words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* replace array Values (string) with length values | |
* @param array $string | |
*/ | |
function get_string_length(&$string){ | |
if ((is_string($string)) || (is_integer($string))) | |
$string = strlen($string); | |
} | |
/** | |
* Trimg string based on number on characters without cutting off words | |
* @param string $string | |
* @param int $length | |
* @param string|null $trailing | |
* @return string | |
*/ | |
function limit_string_length($string,$length=-1,$trailing = null){ | |
if ((strlen($string) > $length) && ($length > 0)){ | |
/* explode string in an array*/ | |
$particles = explode(' ',$string); | |
/*duplicate array*/ | |
$particles_values = $particles; | |
/*replace all strings with their length*/ | |
array_walk($particles_values,'get_string_length'); | |
/*while the sum of all characters bigger than the desired length */ | |
while (array_sum($particles_values) > $length){ | |
/*pop one word from the end of the array*/ | |
array_pop($particles_values); | |
} | |
/*splice our original array to the length of our dummy array*/ | |
$new_particles = array_splice($particles,0,count($particles_values)); | |
/*glue back the array and append to it the desired trailing*/ | |
return implode(' ',$new_particles).$trailing; | |
} | |
return $string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment