<?php
error_reporting(-1);

function checkN($string){
	$reg='/^((\+\s?7\s?)|(\s?8(\W)?))((\W+)?\d(\W)?){10}$/';
	if(preg_match($reg,$string)){return true;}
	else {return false;}
	
}

//tests

$testArray=['84951234567','+74951234567','8-495-1-234-567','8 (8122) 56-56-56','
8-911-1234567','8 (911) 12 345 67','8-911 12 345 67','8 (911) - 123 - 45 - 67','+ 7 999 123 4567','8 ( 999 ) 1234567',
'8 999 123 4567'];
$falseArray=['02','84951234567 позвать люсю','849512345','849512345678','8 (409) 123-123-123','7900123467','5005005001',
'8888-8888-88','84951a234567','8495123456a','+1 234 5678901','+8 234 5678901','7 234 5678901'];

function tester($arr){$matches=0;$mistakes=[];for ($i=0;$i<count($arr);$i++){if(checkN($arr[$i])) {$matches++;}else{array_push($arr[$i],$mistakes);}}return $matches;}
if (tester($testArray)==count($testArray)) {echo "Positive tests passed\n";} else {echo "{$mistakes}";}
if (tester($falseArray)==0){echo "Negative tests passed\n";} else {echo "Only these passed negative tests {$mistakes}\n";}

//tests passed can work with the function further
	
function replacer($string2){$result=NULL;
	if (checkN($string2)){
		$regexp='/[() -]*/'; 
		$re='/^(\+7)/';
		$result=preg_replace($regexp,'',$string2);
		$result=preg_replace('/^(\+7)/','8',$result); 
		echo "$result";
	}
	else {echo "Not a number";}
}
replacer('+7(917)99999999');
?>