dsb0003795 2009-12-26 22:49
浏览 17
已采纳

preg_replace无法正常工作!

Here's my Codeigniter function:

function edit_phone($phone)
{
            if (preg_match('/^\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $phone))
            {
                return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $phone); 
            }
            else
            {
               $this->CI->validation->set_message('phone', "This must be a 10-digit USA phone number.");
                    return FALSE;       
            }
}

This validates/checks the input alright, but doesn't reformat it in the db.

Validation is great! But why isn't this returning a standard phone number?!

  • 写回答

2条回答 默认 最新

  • duanliang4009 2009-12-26 23:18
    关注

    I think the problem is that it will ONLY work with a number in the format 1234567890, but based on the regular expression in the preg_match() call, Kevin is also looking to accommodate numbers like:

    • (123)4567890
    • (123) 456 7890
    • 123-456-7890

    If so, the regex in the preg_replace() needs to be something like...

    preg_replace('/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/', "$1-$2-$3", $phone)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化