note 32516 added to function.substr

From: Date: Fri, 30 May 2003 00:41:07 +0000
Subject: note 32516 added to function.substr
Groups: php.notes 
Request: Send a blank email to php-notes+get-49381@lists.php.net to get a copy of this message
If you are trying to truncate an HTML string, but don't want to break the tags, then use this function, which I found on the web in javascript and converted to PHP. May not be most efficient way, but works nicely. Sorry about tabbing - e-mail me and I will send the nice version. function html_substr ($string, $maxLength) { //---calc the length of string without HTML $noTagLength = strlen(strip_tags($string)); //---parser loop for ($j=0; $j<strlen($string); $j++) { $currentChar=substr($string, $j, 1); $r .= $currentChar; // Lesser than event if ($currentChar == "<") { $isText = false; } // Character handler if ($isText) { // Memorize last space position if ($currentChar == " ") { $lastSpacePosition = $j; } else { $lastChar = $currentChar; } $i++; } else { $currentTag += $currentChar; } // Greater than event if ($currentChar == ">") { $isText = true; // Opening tag handler if (eregi("<", $currentTag) && !eregi("/>", $currentTag) && !eregi("</", $currentTag)) { // Tag has attribute(s) if (eregi(" ", $currentTag)) { $currentTag = substr($currentTag, 1, strpos($currentTag, " ")-1); } else { // Tag doesn't have attribute(s) $currentTag = substr($currentTag, 1, strlen($currentTag-2)); } $tagsArray[$tagLevel] = $currentTag; $tagLevel++; } else if (eregi("</", $currentTag)) { // Closing tag handler $tagsArray[ $tagLevel - 1 ] = null; $tagLevel--; } $currentTag = ""; } if ($i == $maxLength) { break; } } // Cut HTML string at last space position if ($maxLength < $noTagLength) { if ($lastSpacePosition != -1) { $r = substr($string, 0, $lastSpacePosition); } else { $r = substr($string, 0, $j); } } // Close broken XHTML elements for ($a = (count($tagsArray) - 1); $a >= 0; $a--) { if ($tagsArray[$a] != null) { $r += "</" . $tagsArray[$a] . ">"; } } if ($maxLength < $noTagLength) { if ($lastChar != ".") { $r .= "..."; } else { $r .= ".." ;} } return ($r); } ---- Manual Page -- http://www.php.net/manual/en/function.substr.php Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+32516 Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+32516&report=yes Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+32516&report=yes

« previous php.notes (#49381) next »