doushan1850
2018-01-17 05:38
浏览 272

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.

图片转代码服务由CSDN问答提供 功能建议

这是PHP中RGBA值的正则表达式。 它应该同时接受百分比模式和非 -percentage模式。

  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.0 +)\?)“; \  n 
 
 
return(preg_match(“&lt; $ pattern&gt;”,$ color)== 1)?  true:false; 
} 
   
 
 

这适用于此JS测试人员: https://regex101.com/r/A2IjNO/4 但在php中无效。 这有什么问题? 提前谢谢。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    点赞 评论

相关推荐 更多相似问题