php Truncate String to Nearest Space

Recently at work we needed to truncate a string in php. We found some truncate functions online, but we needed to have a bit more zest so I wrote one.

{syntaxhighlighter brush: php;fontsize: 100; first-line: 1; }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);
}{/syntaxhighlighter}

Which can be used like so:

{syntaxhighlighter brush: as3;fontsize: 100; first-line: 1; }$str = “this is a string that is just some text for you to test with”;

print(truncateString($str, 20, true) . “\n”);
print(truncateString($str, 22, true) . “\n”);
print(truncateString($str, 24, true) . “\n”);
print(truncateString($str, 26, true, ” :)”) . “\n”);
print(truncateString($str, 28, true, “–“) . “\n”);{/syntaxhighlighter}

Where the result will look like:

{syntaxhighlighter brush: as3;fontsize: 100; first-line: 1; }/* OUTPUT
this is a string…
this is a string that…
this is a string that…
this is a string that is 🙂
this is a string that is–
*/{/syntaxhighlighter}

Leave a comment

Your email address will not be published.