简体   繁体   中英

PHP Regex: split a string on numeric value

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.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM