note 108976 added to function.strip-tags
| From: | frank at interactinet dot com | Date: | Fri, 08 Jun 2012 18:59:49 +0000 |
| Subject: | note 108976 added to function.strip-tags | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-188477@lists.php.net to get a copy of this message | ||
I used substr() to create a summary... for HTML content this is a problem because of unclosed tags
and broken tags (if the content is cut off in the middle of an open or close tag)
I came up with this... I am not sure it works 100% of the time, but it seems to do the trick.
<pre>
public static function closetags($html)
{
// strip fraction of open or close tag from end (e.g. if we take first x characters, we might cut
off a tag at the end!)
$html = preg_replace('/<[^>]*$/','',$html); // ending with fraction of
open tag
// put open tags into an array
preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$opentags = $result[1];
// put all closed tags into an array
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closetags = $result[1];
$len_opened = count($opentags);
// if all tags are closed, we can return
if (count($closetags) == $len_opened) {
return $html;
}
// close tags in reverse order that they were opened
$opentags = array_reverse($opentags);
// self closing tags
$sc =
array('br','input','img','hr','meta','link');
//
,'frame','iframe','param','area','base','basefont','col'
// should not skip tags that can have content inside!
for ($i=0; $i < $len_opened; $i++)
{
$ot = strtolower($opentags[$i]);
if (!in_array($opentags[$i], $closetags) && !in_array($ot,$sc))
{
$html .= '</'.$opentags[$i].'>';
}
else
{
unset($closetags[array_search($opentags[$i], $closetags)]);
}
}
return $html;
}
</pre>
----
Server IP: 66.207.199.35
Probable Submitter: 68.179.14.105
----
Manual Page -- http://www.php.net/manual/en/function.strip-tags.php
Edit -- https://master.php.net/note/edit/108976
Del: integrated -- https://master.php.net/note/delete/108976/integrated
Del: useless -- https://master.php.net/note/delete/108976/useless
Del: bad code -- https://master.php.net/note/delete/108976/bad+code
Del: spam -- https://master.php.net/note/delete/108976/spam
Del: non-english -- https://master.php.net/note/delete/108976/non-english
Del: in docs -- https://master.php.net/note/delete/108976/in+docs
Del: other reasons-- https://master.php.net/note/delete/108976
Reject -- https://master.php.net/note/reject/108976
Search -- https://master.php.net/manage/user-notes.php