dsgtew3241 2015-04-17 08:24
浏览 42

模式字符串替换的算法(php + regexp)

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;
    }
} 
  • 写回答

1条回答 默认 最新

  • dongxun2089 2015-04-17 08:42
    关注

    $maskes = array( '\b98-\d{3}\(\d{3}\)\b' => '98-###(###)', '\b247\d{4}\b' => '+247-####', ); preg_replace( array_keys($maskes), array_values($maskes), $text );

    But if your phone numbers are stored in a DB, perhaps you can store the country. Then you apply the localized pattern for each phone number. See tools on http://geonames.org Moreover think how you can cache the result when your code is too slow.

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题