Last active
August 11, 2017 08:27
-
-
Save Ellrion/5810b9bb5593555a8348 to your computer and use it in GitHub Desktop.
extended laravel escaping with exclusion some tags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('ex')) { | |
/** | |
* Escape HTML entities in a string with exclusion some tags. | |
* | |
* use in blade template `{!! ex($message, ['br', 'strong']) !!}` | |
* | |
* @param string $str | |
* @param string[] $excluded | |
* @return string | |
*/ | |
function ex($str, array $excluded) | |
{ | |
$patterns = $tags = []; | |
foreach ($excluded as $ex) { | |
$allowed_tag_variants = [ | |
'<' . $ex . '>', //open tag or single tag variant | |
'</' . $ex . '>', //close tag | |
'<' . $ex . ' />', //single tag variant | |
'<' . $ex . '/>', //single tag variant | |
]; | |
foreach ($allowed_tag_variants as $tag) { | |
$patterns[] = '~' . preg_quote(e($tag), '~') . '~'; | |
$tags[] = $tag; | |
} | |
} | |
return preg_replace($patterns, $tags, e($str)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment