Source Code:
(back to article)
<?php function truncate_string_at_word($string, $max_chars) { $string = trim($string); if (strlen($string) > $max_chars) { $string = substr($string, 0, $max_chars); $pos = strrpos($string, " "); if ($pos === false) { return $string; } return substr($string, 0, $pos); } else { return $string; } } $original_string = "This is a very long string that needs to be truncated."; $max_chars = 20; $truncated_string = truncate_string_at_word($original_string, $max_chars); echo $truncated_string; // outputs "This is a very long"
Result:
Report an issue