note 46287 added to language.functions
| From: | com) | Date: | Tue, 05 Oct 2004 20:31:47 +0000 |
| Subject: | note 46287 added to language.functions | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-78043@lists.php.net to get a copy of this message | ||
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*
----
Manual Page -- http://www.php.net/manual/en/language.functions.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+46287
Delete -- http://master.php.net/manage/user-notes.php?action=delete+46287&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+46287&report=yes
Search -- http://master.php.net/manage/user-notes.php