note 33362 added to function.substr

From: Date: Tue, 24 Jun 2003 02:07:44 +0000
Subject: note 33362 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-50907@lists.php.net to get a copy of this message
You can use this function to return x number of _characters_ from a string - I'm sure there's nicer ways than this one too, but here's mine. You can shrink the spacing and chuck out the comments to save space of course, there's not really that much actual code... <?PHP // alex plooy's friendly-format string truncater // reverse each part to contact: xela ~ta~ yoolp ~tod~ ten function substr_index($text, $maxChars = 20, $splitter = '...') { $theReturn = $text; $lastSpace = false; // only do the rest if we're over the character limit if (strlen($text) > $maxChars) { $theReturn = substr($text, 0, $maxChars - 1); // add closing punctuation back in if found if (in_array(substr($text, $maxChars - 1, 1), array(' ', '.', '!', '?'))) { $theReturn .= substr($text, $maxChars, 1); } else { // make room for splitter string and look for truncated words $theReturn = substr($theReturn, 0, $maxChars - strlen($splitter)); $lastSpace = strrpos($theReturn, ' '); // Remove truncated words and trailing spaces if ($lastSpace !== false) { $theReturn = substr($theReturn, 0, $lastSpace); } // Remove trailing commas (add more array elements as desired) if (in_array(substr($theReturn, -1, 1), array(','))) { $theReturn = substr($theReturn, 0, -1); } // append the splitter string $theReturn .= $splitter; } } // all done! return $theReturn; } // e.g. echo substr_index('Hi, I'm very, very happy!', 15); // would output 'Hi, I'm very...' ?> ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+33362 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+33362&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+33362&report=yes

« previous php.notes (#50907) next »