function Xss::split

Same name and namespace in other branches
  1. 8.9.x core/lib/Drupal/Component/Utility/Xss.php \Drupal\Component\Utility\Xss::split()
  2. 10 core/lib/Drupal/Component/Utility/Xss.php \Drupal\Component\Utility\Xss::split()
  3. 11.x core/lib/Drupal/Component/Utility/Xss.php \Drupal\Component\Utility\Xss::split()

Processes an HTML tag.

Parameters

string $string: The HTML tag to process.

array $html_tags: An array where the keys are the allowed tags and the values are not used.

string $class: The called class. This method is called from an anonymous function which breaks late static binding. See https://bugs.php.net/bug.php?id=66622 for more information.

Return value

string If the element isn't allowed, an empty string. Otherwise, the cleaned up version of the HTML element.

File

core/lib/Drupal/Component/Utility/Xss.php, line 143

Class

Xss
Provides helper to filter for cross-site scripting.

Namespace

Drupal\Component\Utility

Code

protected static function split($string, $html_tags, $class) {
    if (substr($string, 0, 1) != '<') {
        // We matched a lone ">" character.
        return '&gt;';
    }
    elseif (strlen($string) == 1) {
        // We matched a lone "<" character.
        return '&lt;';
    }
    if (!preg_match('%^<\\s*(/\\s*)?([a-zA-Z0-9\\-]+)\\s*([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
        // Seriously malformed.
        return '';
    }
    $slash = trim($matches[1]);
    $elem =& $matches[2];
    $attributes =& $matches[3];
    $comment =& $matches[4];
    if ($comment) {
        $elem = '!--';
    }
    // Defer to the ::needsRemoval() method to decide if the element is to be
    // removed. This allows the list of tags to be treated as either a list of
    // allowed tags or a list of denied tags.
    if ($class::needsRemoval($html_tags, $elem)) {
        return '';
    }
    if ($comment) {
        return $comment;
    }
    if ($slash != '') {
        return "</{$elem}>";
    }
    // Is there a closing XHTML slash at the end of the attributes?
    $attributes = preg_replace('%(\\s?)/\\s*$%', '\\1', $attributes, -1, $count);
    $xhtml_slash = $count ? ' /' : '';
    // Clean up attributes.
    $attr2 = implode(' ', $class::attributes($attributes));
    $attr2 = preg_replace('/[<>]/', '', $attr2);
    $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
    return "<{$elem}{$attr2}{$xhtml_slash}>";
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.