Tag Archives: color

Check if rgb(a) or hex color is in correct format

function color_format($i){
        
$pattern = "/^rgb/i";
$pattern2 ="/a/i";
 $i = strtolower($i);
//its rgb
if (preg_match($pattern, $i)){
  
      // is ending with ; 
  $no_need = substr( $i, -1 );
      // is ending with ;
    if($no_need==";") {
      $i = substr($i,0,-1);
       
    } 
    // let's split "("
       $needed_piece = explode("(", $i);
  
  //it's rgb
      if (preg_match($pattern2, $i)){
         $needed_color = "rgba(".$needed_piece[1];
      } else {
         $needed_color = "rgb(".$needed_piece[1];
      }
     
       return $needed_color;

} else{
    
   // is ending with ;
    $no_need = substr( $i, -1 );

    if($no_need==";") {
      $i = substr($i,0,-1);
       
    } 
    
    // is starting with #
 $i= ltrim($i, '#');
 if (
          ctype_xdigit($i) &&
          (strlen($i) == 6 || strlen($i) == 3))
           return $needed_color = "#".$i;


  else return false;
    

}

}