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.

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);
}

Which can be used like so:

$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");

Where the result will look like:

/* 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--
*/

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <p> <pre>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".
  • Lines and paragraphs break automatically.
  • E-Mail addresses are hidden with reCAPTCHA Mailhide.

More information about formatting options

CAPTCHA
Complete this form and then pat yourself on the back.