dongmi4035 2012-10-03 18:26
浏览 40
已采纳

用数组值替换字符串中的字符

I have the following array

static public $tabla = array(
            'A'=>2, 'B'=>2, 'C'=>2,
            'D'=>3, 'E'=>3, 'F'=>3,
            'G'=>4, 'H'=>4, 'I'=>4,
            'J'=>5, 'K'=>5, 'L'=>5,
            'M'=>6, 'N'=>6, 'O'=>6,
            'P'=>7, 'Q'=>7, 'R'=>7,
            'S'=>8, 'T'=>8, 'U'=>8,
            'V'=>9, 'W'=>9, 'X'=>9,
            'Y'=>0, 'Z'=>0
            );

And several strings consisting of alphanumeric characters, for example: "G20513F4561B". What is most efficient way of replacing the non-numeric characters in string by its equivalence according the given array?

I know this can be easily implemented using a loop but maybe there is some kind of regular expression that does the trick.

Thanks

  • 写回答

2条回答 默认 最新

  • douhan4093 2012-10-03 18:34
    关注

    Try strtr():

    echo strtr($str, self::$tabla);
    

    Keys will be replaced with their corresponding values.

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

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动