有没有更好的方法来编写这个IF语句? [关闭]

if($colour && 
      ((strlen($colour) == 7 && preg_match("/#[0-9a-fA-F]{6}/",$colour)) ||
       (strlen($colour) == 4 && preg_match("/#[0-9a-fA-F]{3}/",$colour)))) {
  • If $colour has a value AND
    • $colour is a 7 digit string and conforms to the 7 digit hex colour format OR
    • $colour is a 4 digit string and conforms to the 4 digit hex colour format

(String lengths include hash, hence 3 & 6 become 4 & 7)

Yes, there are. If you use RegEx, you can just as well use one regex, like this. The length can be skipped too, by using start or string/end of string anchors.

if ($colour && preg_match("/^#([0-9a-fA-F]){3}(([0-9a-fA-F]){3})?$/", $colour)
{
}

I think the 'check for value' can be skipped to, but that might make sense as an optimization.

[edit]

It turns out to be an example on the RegEx cheat sheet.

Your regexp already specify stings' lenghts so you do not need to check it if you set start ^ and end $ boundaries:

if ( preg_match("/^#[0-9a-fA-F]{6}$/", $colour) || preg_match("/^#[0-9a-fA-F]{3}$/",$colour) ) {}

You could anchor your regex with ^ and $ so the length is implied.

if( $colour && 
    (  preg_match("/^#[0-9a-fA-F]{6}$/",$colour)
    || preg_match("/^#[0-9a-fA-F]{3}$/",$colour)
  ) ) {

I don't know php that well, but in perl you would need to escape the $ as \$ or use single quotes instead.

Let your regular expressions check the length of the string by adding the ^ and $ signs signaling start/end of a string, and combining your regular expressions:

if (preg_match("/^#[0-9a-fA-F]{3}|#[0-9a-fA-F]{6}$/", $colour)) {
if (preg_match("/^#([0-9a-f]{3}){1,2}$/i", $colour)) {

seems enough to me.