preg_split() String into Text and Numbers [duplicate]

假如想象 提交于 2019-12-02 11:10:52

问题


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

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

output:

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

回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/25285807/preg-split-string-into-text-and-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!