Skip to content

Instantly share code, notes, and snippets.

@Ellrion
Last active August 11, 2017 08:27
Show Gist options
  • Save Ellrion/5810b9bb5593555a8348 to your computer and use it in GitHub Desktop.
Save Ellrion/5810b9bb5593555a8348 to your computer and use it in GitHub Desktop.
extended laravel escaping with exclusion some tags
<?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