Skip to content

Instantly share code, notes, and snippets.

@Stoakes
Last active April 19, 2016 06:06
Show Gist options
  • Save Stoakes/21cc678418190a0d43a2340d44447693 to your computer and use it in GitHub Desktop.
Save Stoakes/21cc678418190a0d43a2340d44447693 to your computer and use it in GitHub Desktop.
<?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