note 33362 deleted from function.substr by nlopess

From: Date: Sat, 03 Jul 2004 11:49:00 +0000
Subject: note 33362 deleted from function.substr by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-72406@lists.php.net to get a copy of this message
Note Submitter: alex plooy ---- 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...' ?>

« previous php.notes (#72406) next »