note 33737 added to function.substr
| From: | php-general at lists dot php dot net | Date: | Sat, 05 Jul 2003 22:39:10 +0000 |
| Subject: | note 33737 added to function.substr | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-51571@lists.php.net to get a copy of this message | ||
If you want to substring the middle of a string with another and keep the words intact:
<?php
/**
* 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@ethinkn.com
* @author loic@.xhtml.ne
* @author arne.hartherz@gmx.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 ($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 ($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);
}
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf
sadf sad s', 30) . "\n";
// Returns: ABCDEEF GHIJK[...]asdf sadf sad s (33 chrs)
echo strMiddleReduceWordSensitive ('ABCDEEF GHIJK LLKJHKHKJHKL HGHFK sdfasdfsdafsdf sadf asdf
sadf sad s', 30, '...') . "\n";
// Returns: ABCDEEF GHIJK...asdf sadf sad s (32 chrs)
?>
----
Manual Page -- http://www.php.net/manual/en/function.substr.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33737
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33737&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33737&report=yes