Skip to content

Instantly share code, notes, and snippets.

@ostretsov
Created February 8, 2016 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostretsov/78355998c2beb57dd7c5 to your computer and use it in GitHub Desktop.
Save ostretsov/78355998c2beb57dd7c5 to your computer and use it in GitHub Desktop.
<?php
/**
* (c) Artem Ostretsov <artem@ostretsov.ru>
* Created at 25.01.2016 11:22
*/
namespace SP\MainBundle\Util;
class StringUtil
{
/**
* @param string $text
* @param array $availableHtmlTags
* @param array $availableAttributes
* @return string
*/
public static function stripTagsAndAttrs($text, array $availableHtmlTags, array $availableAttributes = ['href', 'src', 'style'])
{
$availableHtmlTags = '<'.implode('><', $availableHtmlTags).'>';
$text = strip_tags($text, $availableHtmlTags);
$result = preg_replace_callback(
'/<([a-zA-Z]+.*?)>/ui',
function ($matches) use ($availableAttributes) {
$tagParts = $matches[1];
$trailing = '';
if (mb_substr($matches[1], -1) == '/') {
$tagParts = mb_substr($matches[1], 0, -1);
$trailing = '/';
}
$tagParts = preg_replace_callback(
'/[\'\"](.*?)[\'\"]/',
function ($matches) {
return str_replace(' ', '#&#&#', $matches[0]);
},
$tagParts
);
$tagParts = array_map(
'trim',
explode(' ', str_replace('=', ' = ', $tagParts))
);
$tag = array_shift($tagParts);
$tagParts = array_filter(
$tagParts,
function ($e) {
return !empty($e);
}
);
// get all attributes and their values
$tagParts = array_values($tagParts);
$attrs = [];
while (count($tagParts) > 0) {
foreach ($tagParts as $position => $token) {
if ($token == '=') {
if (isset($tagParts[$position - 1]) && isset($tagParts[$position + 1])) {
$attrs[$tagParts[$position - 1]] = $tagParts[$position + 1];
}
unset ($tagParts[$position]);
if (isset($tagParts[$position - 1])) {
unset ($tagParts[$position - 1]);
}
if (isset($tagParts[$position + 1])) {
unset ($tagParts[$position + 1]);
}
continue 2;
} else {
continue;
}
}
break;
}
foreach ($tagParts as $token) {
$attrs[$token] = null;
}
foreach ($attrs as $key => $value) {
if (!in_array($key, $availableAttributes)) {
unset($attrs[$key]);
}
}
$result[] = $tag;
foreach ($attrs as $key => $value) {
$attr = !empty($value) ? $key.'='.$value : $key;
$result[] = str_replace('#&#&#', ' ', $attr);
}
return '<'.implode(' ', $result).$trailing.'>';
},
$text
);
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment