preg_split()字符串到文本和数字

时间:2014-08-13 12:10:27

标签: php regex preg-match preg-split

我想将字符串分成数字和文本分开。

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

输出:

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

2 个答案:

答案 0 :(得分:1)

通过使用[^0-9]+,您实际上是匹配数字并拆分它们,这会留下一个空数组元素而不是预期结果。您可以使用变通方法来执行此操作。

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

\K动词告诉引擎删除与要返回的匹配项相匹配的内容。

如果您希望始终使用较大的文本执行此操作,则需要多个外观。

print_r(preg_split('/(?<=\D)(?=\d)|\d+\K/', '12345hello6789foo123bar'));
# Array ([0] => 12345 [1] => hello [2] => 6789 [3] => foo [4] => 123 [5] => bar)

答案 1 :(得分:0)

您可以在非数字后用数字Lookahead and Lookbehind拆分,反之亦然。

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

说明:

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

这是online demo

详细模式说明:

  (?<=                     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