Search code examples
javascriptphpregexrgba

Regular expression for RGBA value in php


This is my regular expression for RGBA value in PHP. It is supposed to accept both the percentage pattern and the non-percentage pattern.

function isValidColor_RGBA($color){


$pattern = "rgba\(
         ((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}
         ((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)
         (,\s*(0\.\d+|1))
         \)
        |rgba\(((\d|[1-9]\d|100)%\,\s?){3}(0|0?\.\d+|1|1\.0+)\)";



return (preg_match("<$pattern>", $color) == 1)? true : false;
}

This works in this JS tester: https://regex101.com/r/A2IjNO/4 but didn't work in php. What's wrong with this? Thanks in advance.


Solution

  • Can you try removing the new lines and unwanted spaces?

    I tried with the below expression in www.regex101.com

    ^(#[\da-f]{3}|#[\da-f]{6}|rgba(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2} ((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)(,\s*(0.\d+|1)))|hsla(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)(,\s*(0.\d+|1)))|rgb(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)|hsl(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)))$

    It seems like the new lines and spaces making issues with PHP regex validation. The expression will work on both js and PHP

    I tried the below code in enter link description here

    $pattern = '/^(\#[\da-f]{3}|\#[\da-f]{6}|rgba\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2} ((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)(,\s*(0\.\d+|1))\)|hsla\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)(,\s*(0\.\d+|1))\)|rgb\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)|hsl\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)\))$/';
    $color = 'rgba(222, 222, 222, 0.5)';
    var_dump(preg_match($pattern, $color));
    

    Keep in mind that you need to add white spaces. Because, you added \s before/after the comma symbols