<?php
class ISBN {
# Converts an ISBN-10 to ISBN-13.
# For more information about ISBN-10 to ISBN-13 conversion see:
# http://www.bisg.org/isbn-13/conversions.html
#
public function isbn_10_to_isbn_13( $isbn_10 ) {
if( !$this->is_valid_isbn_10($isbn_10) ) {
return false;
}
$isbn_13= '978' . $isbn_10;
$sum=0;
for( $i= 13; $i > 1; $i-- ) {
$sum+= ((int)$isbn_13{13 - $i}) * ((($i % 2) == 0) ? 3 : 1);
}
$isbn_13{12}= (($sum % 10) == 0) ? 0 : (10 - ($sum % 10));
return $isbn_13;
}
# Removes any "white spaces" and hyphens from an ISBN-10 string.
# Because of the possibility of 'x' or 'X' in ISBN, you should not use the "\D" option.
#
public function clean_isbn_10( $str ) {
$pattern = '/[\s|-]/';
$replacement = '';
return preg_replace( $pattern, $replacement, $str );
}
# Validates an ISBN-10 number using the check digit.
# Use clean_isbn_10 function on the ISBN-10 string before calling this function.
# For more information see about ISBN-10 numbers see:
# http://www.isbn.org/standards/home/isbn/international/html/usm4.htm
#
public function is_valid_isbn_10( $isbn_10 ) {
# Note, isbn-10 has 'X' or 'x' as a check digit signifying the number 10
if( !ereg('^([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9xX])$', $isbn_10) ) {
return false;
}
$sum= 0;
for( $i= 10; $i > 1; $i-- ) {
$sum+= ((int)$isbn_10{10 - $i}) * $i;
}
$sum+= ereg('[xX]$', $isbn_10) ? 10 : ( (int)$isbn_10{9} );
return ( ($sum % 11) == 0 );
}
# Removes any non-numeric characters from an ISBN-13/EAN string.
#
public function clean_isbn_13( $str ) {
$pattern = '/\D/';
$replacement = '';
return preg_replace( $pattern, $replacement, $str );
}
# Validates an EAN number using the check digit. Note ISBN-13 numbers are a subset of EAN numbers.
# For more information about ISBN-13 see:
# http://www.bisg.org/isbn-13/conversions.html
#
public function is_valid_isbn_13( $isbn_13 ) {
# If you want to strictly validate ISBN-13 numbers substitute this line of code in the IF statement:
# !ereg('^((978|979)[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])$', $isbn_13)
if( !ereg('^([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])$', $isbn_13) ) {
return false;
}
$sum= 0;
for( $i= 13; $i > 0; $i-- ) {
$sum+= ((int)$isbn_13{13 - $i}) * ((($i % 2) == 0) ? 3 : 1);
}
return ( ($sum % 10) == 0 );
}
}
?>
Regards,
drenintell
1 comments:
Excellent work. Perfect for covering my old database of ASIN/ISBN10 to ISBN13. Especially since Amazon canceled my Colorado based associates account.
--RayJ
Post a Comment