note 103925 added to function.substr
| From: | frederic dot leroy at adeqweb dot com | Date: | Wed, 11 May 2011 15:05:42 +0000 |
| Subject: | note 103925 added to function.substr | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179608@lists.php.net to get a copy of this message | ||
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;
}
----
Server IP: 69.147.83.197
Probable Submitter: 90.46.12.121
----
Manual Page -- http://www.php.net/manual/en/function.substr.php
Edit -- https://master.php.net/note/edit/103925
Del: integrated -- https://master.php.net/note/delete/103925/integrated
Del: useless -- https://master.php.net/note/delete/103925/useless
Del: bad code -- https://master.php.net/note/delete/103925/bad+code
Del: spam -- https://master.php.net/note/delete/103925/spam
Del: non-english -- https://master.php.net/note/delete/103925/non-english
Del: in docs -- https://master.php.net/note/delete/103925/in+docs
Del: other reasons-- https://master.php.net/note/delete/103925
Reject -- https://master.php.net/note/reject/103925
Search -- https://master.php.net/manage/user-notes.php