doupuzhimuhan9216 2014-12-13 14:34
浏览 23
已采纳

PHP正则表达式:在数值上拆分一个字符串

I have a code that can receive 2 types of string:

  1. text number text

    danny levitt 48 new york
    
  2. text number [comma] text

    danny levitt 48, new york
    

The text on both size can be a single word or more, and the language might not be english.

I need those strings to return to me in an array as follows:

    Array (
        0 => "danny levitt",
        1 => "48",
        2 => "new york"
    )

How can I do that?

Thanks.

  • 写回答

1条回答 默认 最新

  • douzhuo5671 2014-12-13 14:46
    关注

    Split your input according to the space which exists just before to the number and the space which follows the same number. \K discards the previously matched characters.

    $string = "danny levitt 48, new york";
    $regex = '~\s+(?=\b\d+,?)|\b\d+\K,?\s+~';
    $splits = preg_split($regex, $string);
    print_r($splits);
    

    Output:

    Array
    (
        [0] => danny levitt
        [1] => 48
        [2] => new york
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳