[ create a new paste ] login | about

Link: http://codepad.org/uRwkHdsJ    [ raw code | output | fork ]

PHP, pasted on Apr 10:
Truncates to nearest preceding space of target character.

<?php

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

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

?>


Output:
1
2
3
4
5
6
7
Truncates to nearest preceding space of target character.

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


Create a new paste based on this one


Comments: