A better substring function

// This function does not destroy i.e. html entities which could lead to a wrecked design or strange custom chars showing on a site // It iterates backward through the string and checks for a space or a minus sign and cuts the string at that position. // The result will be a clean string that does not exceed the maximum char specification. Furthermore it adds some dots and a right arrow // to indicate, there's more to read function substr2($string,$len){ $str = strip_tags($string); $el_on_pos = $str[$len-1]; $found = false; $loop = $len-1; if($el_on_pos != ' ' || $el_on_pos != '-'){ while(!$found){ if($str[$loop] == ' ' || $str[$loop] == '-' ){ $found = 1; $diff = $len-$loop; echo substr($str,0,$loop); for($i=0;$i<$diff-1;$i++){ echo "."; } } $loop--; } }else{ echo substr($str,0,$len); } }

2 Responses

$subs = preg_split("/[s,-]+/", $string, $len);
echo implode(, $subs);

// ... no?
implode(" ", $subs); // ... no?

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.