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.

我有一个代码可以接收两种类型的字符串: p>

    \ n
  1. 文本编号文本 p>

      danny levitt 48 new york 
      code>  pre>  li> 
     
  2. 文本编号[逗号]文本 p>

      danny levitt 48,new york 
      code>  pre>  li> 
      ol> 
     \  n 

    两个大小的文本都可以是一个单词或更多,语言可能不是英语。 p>

    我需要这些字符串在数组中返回给我,如下所示: p>

      Array(
     0 =>“danny levitt”,
     1 =>“48”,
     2 =>“new york”
    )  
      code>  pre> 
     
     

    我该怎么做? p>

    谢谢。 p> div>

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
)