Skip to content

Instantly share code, notes, and snippets.

@oppara
Last active October 25, 2015 06:04
Show Gist options
  • Save oppara/102087 to your computer and use it in GitHub Desktop.
Save oppara/102087 to your computer and use it in GitHub Desktop.
php: htmlescape but $tags
<?php
/**
* htmlescape but $tags
*
* @see http://jp.php.net/manual/ja/function.htmlspecialchars.php
* @param string $str
* @param string $tags delimiter "|". i.e. 'a|div|span'
* @param string $quote_style
* @param string $l_deli '##{##'
* @param string $r_deli '##}##'
* @access public
* @return string
*/
function htmlescape( $str, $tags = '', $quote_style = ENT_NOQUOTES, $l_deli = '##{##', $r_deli = '##}##' ) {
if ( !$tags ) {
return htmlspecialchars( $str, $quote_style );
}
$reg = '#<(/?[^<>]*\b(?:' . $tags . ')\b[^<>]*)>#ie';
$buf = preg_replace( $reg, "_htmlescape('$l_deli\\1$r_deli')", $str );
$buf = htmlspecialchars( $buf, $quote_style );
$searches = array(
$l_deli,
$r_deli,
);
$replacements = array(
'<',
'>',
);
return str_replace( $searches, $replacements, $buf );
}
function _htmlescape( $match ) {
$order = array(
"\r\n",
"\n",
"\r",
);
$match = str_replace( $order, '', $match );
$match = str_replace( '\"', '"', $match );
return $match;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment