Here's how I would personally approach using MySQL data to build Regex patterns for checking data:
//Simplified array
$dbResults = array(
array(
'id' => 1,
'extension' => 1005,
'order' => 1,
'description' => 'rule 1',
'ruledigits' => '9XX',
'prefix' => null,
'ruletype' => 'Block'
),
array(
'id' => 2,
'extension' => 1005,
'order' => 2,
'description' => 'rule 2',
'ruledigits' => '302NXXXXXX',
'prefix' => 1,
'ruletype' => 'Mod'
),
array(
'id' => 3,
'extension' => 2005,
'order' => 3,
'description' => 'rule 3',
'ruledigits' => '00Z',
'prefix' => '001',
'ruletype' => 'Mod'
)
);
$regexParts = array(
'N' => '[2-9]'
,'Z' => '\d*'
,'X' => '\d'
,'x' => '\d'
);
//Static test vars
$userExt = 1005;
$dialTests = array('00325698289115','908','3025555555');
echo 'Testing user extension: '.$userExt;
echo '<br /><br />';
//This loop is for testing purposes only, the contents are all the live system would use
foreach($dialTests as $testNo)
{
$actionTaken = 'None';
//By default, if nothing happens, make sure the final number is the original one we saw
$finalNo = $testNo;
foreach($dbResults as $row)
{
if($userExt != $row['extension']) continue;//If it's not the right extension, skip the rest of this loop iteration's code and move on to the next row
$regex = '';
$tokens = str_split($row['ruledigits']);//Turn the string into an array, so we can parse each character individually
foreach($tokens as $token)
{
if(isset($regexParts[$token])) $regex .= $regexParts[$token];//If the letter has a special meaning, use that
else $regex .= $token;//else just throw that exact letter/number in
}
if(preg_match('#^'.$regex.'$#',$testNo)>0)
{
$actionTaken = $row['ruletype'];//Log what action has been taken
if($actionTaken=='Mod')
{
$finalNo = $row['prefix'].$testNo;//Do the mod action
}
else if($actionTaken=='Block')
{
$finalNo = false;//Nullify the final number, so we know to block the call later on
}
}
}
//Here we just dump some info for testing purposes
echo $testNo.': Action taken = '.$actionTaken;
if($actionTaken=='Block') echo ' - Call terminated.';
if($actionTaken=='Mod') echo ' - New number = '.$finalNo;
echo '<hr />';
}
View the output demo on phpfiddle (click Run/F9)