I have several hundreds of special code templates, like:
array(
'mask' => '98-###(###)',
'detect' => '98-\d\d\d(\d\d\d)',
),
...
And input strings (only digits), what is a best way to detect and format (replacing #
to digits from input string) codes? My algorithm works, but its very slow (I need format codes for each request) - Can anyone see how it could be improved:
<?php
class PCode
{
private static $vector = array (
0 => array (
'detect' => '247\\d\\d\\d\\d',
'mask' => '+247-####',
), // <<<<< more codes here
);
/**
*
* @param unknown $phs
* @return string
*/
public static function format($phn)
{
$result = $phn;
foreach(self::$vector as $row)
{
if(preg_match('/'.$row['detect'].'/s', $phn))
{
$reverse = array_reverse( str_split($phn) );
$reverseMask = array_reverse( str_split($row['mask']) );
$newresult = array();
$ridx = 0;
foreach($reverseMask as $k)
{
if($k=='#')
{
$newresult[] = $reverse[$ridx];
$ridx++;
}
else
$newresult[] = $k;
}
$result = implode('', array_reverse( $newresult ));
}
}
return $result;
}
}