php-regexHow to use PHP regex to match a hex color?
To match a hex color with PHP regex, you can use the following code:
$hex_color = "#FFF";
if (preg_match('/^#[a-f0-9]{6}$/i', $hex_color)) {
echo "Valid hex color";
} else {
echo "Invalid hex color";
}
The output of this code will be:
Valid hex color
The code consists of the following parts:
$hex_color = "#FFF";
- this is the variable containing the hex color to be matched.preg_match('/^#[a-f0-9]{6}$/i', $hex_color)
- this is the regular expression used to match the hex color. It matches a string that starts with a#
followed by 6 characters froma-f
or0-9
and ends with the same character. Thei
flag at the end makes the expression case-insensitive.echo "Valid hex color";
- this is the output when the hex color is valid.echo "Invalid hex color";
- this is the output when the hex color is invalid.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a zip code?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
- How to use PHP regex to match an XML tag?
See more codes...