たまには写経を
ISBN は、誤り検出のため各数字の重み付き合計が 11 の倍数になるように最後の数字が調節されている。
最後の数字のみ 10 にしたい場合は X で表す。(via. C言語によるアルゴリズム辞典 P.371)
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; | |
} | |
} |
コメントを残す