-->

preg_split() String into Text and Numbers [duplica

2020-04-24 11:35发布

问题:

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