Last active
April 19, 2016 06:06
-
-
Save Stoakes/21cc678418190a0d43a2340d44447693 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* PHP Class to validate CAS number in chemistry | |
**/ | |
class CasChecker{ | |
private $regex = "#([0-9]{2,7})-([0-9]{2})-[0-9]#"; | |
private function getCheckDigit($cas){ | |
preg_match($this->regex,$cas,$match); | |
$digits = array_reverse(str_split($match[1].$match[2]) ); | |
$sum = 0; | |
for($i =0; $i < count($digits); $i++){ | |
$sum += ($i+1)*$digits[$i]; | |
} | |
return $sum % 10; | |
} | |
private function isValid($cas){ | |
if(!preg_match($this->regex,$cas)){ | |
return false; | |
} | |
return $this->getCheckDigit($cas) == substr($cas,-1); | |
} | |
public function validate($cas){ | |
return $this->isValid($cas); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment