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-for0-9and ends with the same character. Theiflag 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 match a single quote in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match an XML tag?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
- How to use PHP regex to match URL?
- How to use PHP regex to match time?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a year?
- How to use PHP regex with the "x" modifier?
See more codes...