doushan1850 2018-01-17 05:38
浏览 551
已采纳

php中RGBA值的正则表达式

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.

  • 写回答

1条回答 默认 最新

  • douwan2664 2018-01-17 06:13
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题