note 32516 deleted from function.substr by alindeman
| From: | alindeman@php.net | Date: | Fri, 30 May 2003 01:04:12 +0000 |
| Subject: | note 32516 deleted from function.substr by alindeman | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-49382@lists.php.net to get a copy of this message | ||
Note Submitter: dave@daveswave.net
----
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);
}