note 39667 deleted from function.preg-split by tularis
| From: | tularis@php.net | Date: | Thu, 03 May 2007 22:28:32 +0000 |
| Subject: | note 39667 deleted from function.preg-split by tularis | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-126185@lists.php.net to get a copy of this message | ||
Note Submitter: ed_isthmusNOSPAM at yahoo dot com
----
I needed to encode special html characters in strings, but keep some of the tags working! This
function does the deed:
<?php
function html_out_keep_tags ($string) {
$newstring = '';
$pattern = '/(<\/?(?:a .*|h1|h2|b|i)>)/ims';
$newarray = preg_split( $pattern, $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
foreach ($newarray as $element) {
if (!preg_match($pattern, $element))
$element = htmlspecialchars ( html_entity_decode($element, ENT_QUOTES), ENT_QUOTES);
$newstring .= $element;
}
return $newstring;
}
?>
edit $pattern to change the allowed tags.
Note that ?: usefully prevents the sub-pattern from becoming a delimiter. Double encoding is
prevented, see notes on htmlspecialchars().