rest_parse_hex_color()
云策文档标注
概述
rest_parse_hex_color() 函数用于解析带 # 号的 3 位或 6 位十六进制颜色字符串,验证其格式并返回颜色值或 false。
关键要点
- 参数 $color 为必需,必须是带 # 号的 3 位或 6 位十六进制颜色字符串。
- 返回值为字符串(成功时)或 false(失败时)。
- 使用正则表达式验证颜色格式,匹配失败则返回 false。
- 该函数自 WordPress 5.4.0 版本引入。
代码示例
function rest_parse_hex_color( $color ) {
$regex = '|^#([A-Fa-f0-9]{3}){1,2}$|';
if ( ! preg_match( $regex, $color, $matches ) ) {
return false;
}
return $color;
}注意事项
- 用户贡献笔记中提到,该函数功能与较早的 sanitize_hex_color() 函数类似,开发者需注意两者区别。
原文内容
Parses a 3 or 6 digit hex color (with #).
Parameters
$colorstringrequired-
3 or 6 digit hex color (with #).
Source
function rest_parse_hex_color( $color ) {
$regex = '|^#([A-Fa-f0-9]{3}){1,2}$|';
if ( ! preg_match( $regex, $color, $matches ) ) {
return false;
}
return $color;
}
Changelog
| Version | Description |
|---|---|
| 5.4.0 | Introduced. |
Skip to note 2 content
Joy
I wonder why this function was added, when an older function does the same thing.
https://developer.wordpress.org/reference/functions/sanitize_hex_color/