note 103925 deleted from function.substr by danbrown
| From: | danbrown@php.net | Date: | Wed, 11 May 2011 15:40:24 +0000 |
| Subject: | note 103925 deleted from function.substr by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-179618@lists.php.net to get a copy of this message | ||
Note Submitter: frederic dot leroy at adeqweb dot com
----
Maybe this can help a few people around, this is a slight evolution of the mb_substrws function
posted hereafter.
Many thanks to kueb, erez and benny
/**
* Function to return $length first characters from html buffer. HTML tags are not taken into
account in the char count and preserved
* The function expects W3C well formed html, especially regarding self closing tags that MUST
have a space before the closing slash :
* For example, a '<br/>' tag or '<img src=""/>'
tag will not be correctly interpreted, function expects proper '<br />' and
'<img src="" />' (with spaces)
*
* @param string $html: The html to truncate
* @param integer $length : The number of characters to keep in summary (default 250)
* @return string The trunctaed HTML
*/
public static function html_summary($html, $length = 250)
{
if ((mb_strlen($html) > $length))
{
$explodedText = preg_split('/(<[^>]*>| )/', $html, -1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$html = '';
list($index, $word) = each($explodedText);
while ($word && $length > 0)
{
//add this word
$html.=$word;
//only count chars if not a tag
if (!preg_match('/<[^>]*>/', $word))
{
$length-=mb_strlen($word);
}
//get next word
list($index, $word) = each($explodedText);
}
// close unclosed html tags
if (preg_match_all("/(<([\w]+) [^>]*[^\/]>|<([a-zA-Z]+)>)/",
$html, $aBuffer))
{
$openingTags = array();
foreach ($aBuffer[2] as $index => $tagWithOptions)
{
if (!$tagWithOptions)
{
$openingTags[] = $aBuffer[3][$index];
} else
{
$openingTags[] = $tagWithOptions;
}
}
if (!empty($aBuffer[1]))
{
preg_match_all("|</([a-zA-Z]+)>|", $html, $aBuffer2);
$closingTags = $aBuffer2[1];
if (count($openingTags) != count($closingTags))
{
$tagsToClose = array_diff($openingTags, $closingTags);
$tagsToClose = array_reverse($tagsToClose);
foreach ($tagsToClose as $tag)
{
$html .= '</' . $tag . '>';
}
}
}
}
}
return $html;
}