preg_split() String into Text and Numbers [duplica

2020-04-24 10:53发布

i want to split the string into numbers and text as separate.

print_r(preg_split("/[^0-9]+/", "12345hello"));

output:

Array ( [0] => 12345 [1] => ) 

2条回答
Root(大扎)
2楼-- · 2020-04-24 11:42

You can split it with Lookahead and Lookbehind from digit after non-digit and vice verse.

          (?<=\D)(?=\d)|(?<=\d)(?=\D)

explanation:

\D  Non-Digit [^0-9]
\d  any digit [0-9]

Here is online demo

Detail pattern explanation:

  (?<=                     look behind to see if there is:
    \D                       non-digits (all but 0-9)
  )                        end of look-behind
  (?=                      look ahead to see if there is:
    \d                       digits (0-9)
  )                        end of look-ahead

 |                        OR

  (?<=                     look behind to see if there is:
    \d                       digits (0-9)
  )                        end of look-behind
  (?=                      look ahead to see if there is:
    \D                       non-digits (all but 0-9)
  )                        end of look-ahead
查看更多
唯我独甜
3楼-- · 2020-04-24 11:50

By using [^0-9]+ you are actually matching the numbers and splitting on them, which leaves you with an empty array element instead of the expected result. You can use a workaround to do this.

print_r(preg_split('/\d+\K/', '12345hello'));
# Array ([0] => 12345 [1] => hello)

The \K verb tells the engine to drop whatever it has matched so far from the match to be returned.

If you want to consistently do this with larger text, you need multiple lookarounds.

print_r(preg_split('/(?<=\D)(?=\d)|\d+\K/', '12345hello6789foo123bar'));
# Array ([0] => 12345 [1] => hello [2] => 6789 [3] => foo [4] => 123 [5] => bar)
查看更多
登录 后发表回答