dongshuzui0335 2012-11-27 11:45
浏览 32
已采纳

如何以这种格式检查字符串:+ xxx-yyyy-zzzz? [关闭]

X, y, z are all numbers. Beside knowing how to check if the string is 14 chars long, I don't want to iterate each character and check if the char matches [0-9].

Are there smarter ways? No regex pls.... I'm scared of it.

  • 写回答

4条回答 默认 最新

  • doujiaci7976 2012-11-27 11:55
    关注

    You can use sscanf:

    Example:

    print_r( sscanf("+123-1234-1234", "+%3d-%4d-%4d") );
    

    will output:

    Array ( [0] => 123 [1] => 1234 [2] => 1234 )
    

    This will not guarantee the validity of the input string though. A string like +1-1-1 would result in array having all three values with 1. So you still have to validate the three array values separately.

    See the list of supported formats (not sure PHP supports all of these though).

    But seriously, ^\+\d{3}-\d{4}-\d{4}$ is not something to be scared of. It's reasonably simple. There is much worse in Regex Land.

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

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line