note 63230 added to function.substr

From: Date: Thu, 16 Mar 2006 15:45:24 +0000
Subject: note 63230 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-105932@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 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 ($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) ?> ---- Server IP: 81.92.200.26 Probable Submitter: 81.193.168.85 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit -- http://master.php.net/note/edit/63230 Del: integrated -- http://master.php.net/note/delete/63230/integrated Del: useless -- http://master.php.net/note/delete/63230/useless Del: bad code -- http://master.php.net/note/delete/63230/bad+code Del: spam -- http://master.php.net/note/delete/63230/spam Del: non-english -- http://master.php.net/note/delete/63230/non-english Del: in docs -- http://master.php.net/note/delete/63230/in+docs Del: other reasons-- http://master.php.net/note/delete/63230 Reject -- http://master.php.net/note/reject/63230 Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#105932) next »