note 76951 added to function.substr-replace

From: Date: Tue, 07 Aug 2007 19:56:01 +0000
Subject: note 76951 added to function.substr-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-129261@lists.php.net to get a copy of this message
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.) The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me... Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added. <?php function truncate($text,$numb,$etc = "...") { $text = html_entity_decode($text, ENT_QUOTES); if (strlen($text) > $numb) { $text = substr($text, 0, $numb); $text = substr($text,0,strrpos($text," ")); $punctuation = ".!?:;,-"; //punctuation you want removed $text = (strspn(strrev($text), $punctuation)!=0) ? substr($text, 0, -strspn(strrev($text), $punctuation)) : $text; $text = $text.$etc; } $text = htmlentities($text, ENT_QUOTES); return $text; } ?> I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function): <?php function mtruncate($text, $numb, $etc = " ... ") { $first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, ""); $second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, ""); return $first_part.$etc.$second_part; } ?> ---- Server IP: 216.235.15.211 Probable Submitter: 204.244.149.125 ---- Manual Page -- http://www.php.net/manual/en/function.substr-replace.php Edit -- https://master.php.net/note/edit/76951 Del: integrated -- https://master.php.net/note/delete/76951/integrated Del: useless -- https://master.php.net/note/delete/76951/useless Del: bad code -- https://master.php.net/note/delete/76951/bad+code Del: spam -- https://master.php.net/note/delete/76951/spam Del: non-english -- https://master.php.net/note/delete/76951/non-english Del: in docs -- https://master.php.net/note/delete/76951/in+docs Del: other reasons-- https://master.php.net/note/delete/76951 Reject -- https://master.php.net/note/reject/76951 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#129261) next »