What are some best practices for validating ISBN numbers in PHP when working with book data retrieval?

When working with book data retrieval, it's essential to validate ISBN numbers to ensure accuracy and consistency. One common method to validate ISBN numbers in PHP is by using a regular expression to check if the format is correct. Additionally, you can calculate the checksum digit to verify the validity of the ISBN number.

function validateISBN($isbn) {
    $isbn = str_replace(['-', ' '], '', $isbn);

    if (!preg_match('/^\d{9}[\d|X]$/', $isbn)) {
        return false;
    }

    $checksum = 0;
    for ($i = 0; $i < 9; $i++) {
        $checksum += (int)$isbn[$i] * (10 - $i);
    }
    $checksum = ($checksum % 11) == 0 ? 0 : 11 - ($checksum % 11);

    return $isbn[9] === ($checksum == 10 ? 'X' : (string)$checksum);
}

// Example
$isbn = '0-306-40615-2';
if (validateISBN($isbn)) {
    echo 'Valid ISBN';
} else {
    echo 'Invalid ISBN';
}