Are there any best practices for handling and processing color codes in PHP?

When working with color codes in PHP, it's important to ensure that the input is valid and properly formatted. One common issue is handling color codes with or without the "#" symbol at the beginning. To solve this, you can use regular expressions to validate and normalize the color code input.

// Function to validate and normalize color code input
function validateColorCode($colorCode) {
    // Remove "#" symbol if present
    $colorCode = ltrim($colorCode, '#');
    
    // Check if the color code is valid
    if (preg_match('/^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $colorCode)) {
        return '#' . $colorCode; // Return normalized color code with "#" symbol
    } else {
        return false; // Return false for invalid color code
    }
}

// Example of using the function
$colorCode = '#FF0000'; // Input color code
$normalizedColorCode = validateColorCode($colorCode);

if ($normalizedColorCode) {
    echo "Valid color code: " . $normalizedColorCode;
} else {
    echo "Invalid color code";
}