Reduce a string by the middle
Reduce a string by the middle, keeps whole words together
/** * Reduce a string by the middle, keeps whole words together * * @param string $string * @param int $max (default 50) * @param string $replacement (default [...]) * @return string * @author david at ethinkn dot com * @author loic at xhtml dot ne * @author arne dot hartherz at gmx dot net */ function strMiddleReduceWordSensitive($string, $max = 50, $rep = '[...]') { $strlen = strlen($string); if ($strlen <= $max) return $string; $lengthtokeep = $max - strlen($rep); $start = 0; $end = 0; if (($lengthtokeep % 2) == 0) { $start = $lengthtokeep / 2; $end = $start; } else { $start = intval($lengthtokeep / 2); $end = $start + 1; } $i = $start; $tmp_string = $string; while ($i < $strlen) { if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ') { $tmp_string = substr($tmp_string, 0, $i) . $rep; $return = $tmp_string; } $i++; } $i = $end; $tmp_string = strrev ($string); while ($i < $strlen) { if (isset($tmp_string[$i]) and $tmp_string[$i] == ' ') { $tmp_string = substr($tmp_string, 0, $i); $return .= strrev ($tmp_string); } $i++; } return $return; return substr($string, 0, $start) . $rep . substr($string, - $end); }
Snippet Details
-
Authorsee sourcecode (found in an php.net comment)
-
License?
-
LanguagePHP
-
Created04/05/2006
-
Updated04/05/2006
-
Tagsstring functions, texts
// example: $text = 'This is a very long test sentence, bla foo bar nothing'; print strMiddleReduceWordSensitive ($text, 30) . "\n"; // Returns: This is a very[...]foo bar nothing (~ 30 chrs) print strMiddleReduceWordSensitive ($text, 30, '...') . "\n"; // Returns: This is a very...foo bar nothing (~ 30 chrs)
Sorry folks, comments have been deactivated for now due to the large amount of spam.
Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!
Older comments:
mohsen February 19, 2008 at 03:08
same??
function strMiddleReduceWordSensitive($string, $max = 50, $rep = '[...]') {
$strLen = strlen($string);
$difLen = $strLen - $max;
$leftText = substr($string, 0, $max/2);
$repText = substr($string, $max/2, $difLen);
$string = str_replace($repText, $rep, $string);
$string = str_replace($leftText, rtrim($leftText), $string);
return $string;
}
function strMiddleReduceWordSensitive($string, $max = 50, $rep = '[...]') {
$strLen = strlen($string);
$difLen = $strLen - $max;
$leftText = substr($string, 0, $max/2);
$repText = substr($string, $max/2, $difLen);
$string = str_replace($repText, $rep, $string);
$string = str_replace($leftText, rtrim($leftText), $string);
return $string;
}