preg_split() 字符串转换成文本和数字 [英] preg_split() String into Text and Numbers

查看:51
本文介绍了preg_split() 字符串转换成文本和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串拆分为单独的数字和文本.

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

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

输出:

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

推荐答案

通过使用 [^0-9]+ 您实际上是在匹配数字并对其进行拆分,这会留下一个空白数组元素而不是预期的结果.您可以使用一种解决方法来执行此操作.

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)

\K 动词告诉引擎从要返回的匹配项中删除到目前为止已匹配的任何内容.

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)

这篇关于preg_split() 字符串转换成文本和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆