wp_kses_hair()
Gets a list of HTML tag attributes (as an array) from the provided string with attributes.
This function does a lot of work. In addition to processing the string and creating an array of the attributes contained in it, it also adds quotes if they are not specified in the attributes. Additionally, it removes unspecified, thus prohibited protocols (http) from the attribute values if it is a URL. It also removes duplicate attributes, so that foo=bar foo=baz becomes foo="bar".
Although the function relates to cleaning functions (kses), it is convenient to use in plugins when it is necessary to process tag attributes, which is often needed.
No Hooks.
Returns
Array
Usage
wp_kses_hair( $attr, $allowed_protocols );
- $attr(string) (required)
- HTML tag attributes, exactly as they are specified in the attribute. Multiple spaces are ignored.
- $allowed_protocols(array) (required)
- Allowed protocols that should be retained if there are URLs in the attribute values.
Examples
#1 Demonstration of work
$attrs = wp_kses_hair(' src="http://example.com/jpg.jpg" alt="aaaaa" foo=bar', 'http');
/*
$attrs will contain:
Array
(
[src] => Array
(
[name] => src
[value] => http://example.com/jpg.jpg
[whole] => src="http://example.com/jpg.jpg"
[vless] => n
)
[alt] => Array
(
[name] => alt
[value] => aaaaa
[whole] => alt="aaaaa"
[vless] => n
)
[foo] => Array
(
[name] => foo
[value] => bar
[whole] => foo="bar"
[vless] => n
)
)
*/ #2 Protocol, which is different from the value of the attribute
If you specify a protocol that will be different, the function simply removes the protocol leaving the URL relative:
$attrs = wp_kses_hair('src=http://example.com/jpg.jpg', 'https');
/*
We get it:
Array
(
[src] => Array
(
[name] => src
[value] => //example.com/jpg.jpg
[whole] => src="//example.com/jpg.jpg"
[vless] => n
)
)
*/
Changelog
| Since 1.0.0 | Introduced. |
| Since 7.0.0 | Reliably parses HTML via the HTML API. |