Created
February 19, 2013 16:16
-
-
Save wokamoto/4987314 to your computer and use it in GitHub Desktop.
[PHP] ISBN のチェック
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
var_dump(validISBN('4-87408-414-1')); | |
function validISBN($isbn) { | |
if (preg_match('/^(\d)-?(\d)-?(\d)-?(\d)-?(\d)-?(\d)-?(\d)-?(\d)-?(\d)-?([\dX])$/i', $isbn, $d)) { | |
$d[0] = 0; | |
foreach ( $d as $key => &$val ) { | |
$val = ($key == 10 && ($val == 'x' || $val == 'X')) ? 10 : intval($val); | |
} | |
for ( $i = 1; $i <= 10; $i++ ) { | |
$d[$i] += $d[$i - 1]; | |
} | |
for ( $i = 1; $i <= 10; $i++ ) { | |
$d[$i] += $d[$i - 1]; | |
} | |
return ($d[10] % 11 == 0); | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ISBN は、誤り検出のため各数字の重み付き合計が 11 の倍数になるように最後の数字が調節されている。
最後の数字のみ 10 にしたい場合は X で表す。
これは正しいISBNかチェックするための関数 (via. C言語によるアルゴリズム辞典 P.371)