To the nearest space
Truncates to the nearest preceding space of the target character. Demo
$str String to be truncated$chars number of characters to be deleted can be overridden $to_space$to_space boolean in order to truncate from space around $chars limit
Function
function truncateString($str, $chars, $to_space, $replacement="...") { if($chars > strlen($str)) return $str; $str = substr($str, 0, $chars); $space_pos = strrpos($str, " "); if($to_space && $space_pos >= 0) $str = substr($str, 0, strrpos($str, " ")); return($str . $replacement); }
Example
<?php $str = "this is a string that is just some text for you to test with"; print(truncateString($str, 20, false) . "\n"); print(truncateString($str, 22, false) . "\n"); print(truncateString($str, 24, true) . "\n"); print(truncateString($str, 26, true, " :)") . "\n"); print(truncateString($str, 28, true, "--") . "\n"); ?>
Exit
this is a string tha... this is a string that ... this is a string that... this is a string that is :) this is a string that is--
Jacksonkr Apr 10 2018-12-12T00: 00Z
source share