note 46287 deleted from language.functions by aidan

From: Date: Sat, 09 Oct 2004 05:27:07 +0000
Subject: note 46287 deleted from language.functions by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-78209@lists.php.net to get a copy of this message
Note Submitter: drenintell-(at)_gmail_(dot)-(com) ---- Here is a function to check if a 10 digit ISBN number is valid using the chech digit. This function takes into account if the check digit is X or x. <?php function is_isbn($isbn) { $sum= 0; for($i= 10; $i > 1; $i--) { $sum+= ((int)$isbn{10 - $i}) * $i; } $sum+= eregi('x$', $isbn) ? 10 : ((int)$isbn{9}); return (($sum % 11) === 0); } ?> Before you use the function make sure the following: 1. You remove any hyphens from the isbn. You could use ereg_replace('-', '', $isbn); 2. Make sure the length of the ISBN is 10 characters long. In particular, the first 9 characters must be digits [0-9] and the last character must be a digit [0-9] or an X or x. I think you could use this regular expression eregi('^[0-9]{9}[[0-9]|x]$', $isbn) to check that. Here is the improved version and bellow that are tests to verify functionality: <?php function is_isbn($isbn) { $isbn= ereg_replace('-', '', $isbn); if(!eregi('^[0-9]{9}[[0-9]|x]$', $isbn)) { return false; } $sum= 0; for($i= 10; $i > 1; $i--) { $sum+= ((int)$isbn{10 - $i}) * $i; } $sum+= eregi('x$', $isbn) ? 10 : ((int)$isbn{9}); return (($sum % 11) === 0); } echo is_isbn('0-8436-1072-7') ? 'valid' : 'invalid'; echo "\n"; echo is_isbn('0-07-219443-X') ? 'valid' : 'invalid'; echo "\n"; echo is_isbn('a-8436-1072-7') ? 'valid' : 'invalid'; echo "\n"; echo is_isbn('0-8436-1072-8') ? 'valid' : 'invalid'; echo "\n"; echo is_isbn('0843610728') ? 'valid' : 'invalid'; echo "\n"; echo is_isbn('0843610727') ? 'valid' : 'invalid'; echo "\n"; ?> The output should be: valid invalid invalid invalid invalid valid Let me know if you encounter a problem with this function. Regards, George A. P. *drenintell*

« previous php.notes (#78209) next »