将字符串拆分为文本和数字 [英] Split String into Text and Number

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

问题描述

我有一些可以采用以下格式的字符串

I have some strings which can be in the following format


sometext moretext 01 text
text sometext moretext 002
text text 1 (somemoretext)
etc

我想将这些字符串拆分为以下内容:数字和数字之前的文本

I want to split these strings into following: text before the number and the number

例如:文字文字1(somemoretext)
拆分时将输出:
文字=文字文字
数字= 1

号码后的任何东西都可以丢弃

For example: text text 1 (somemoretext)
When split will output:
text = text text
number = 1

Anything after the number can be discarded

已经阅读了有关使用正则表达式的信息,并且可能使用了preg_match或preg_split,但在正则表达式部分却迷路了

Have read up about using regular expressions and maybe using preg_match or preg_split but am lost when it comes to the regular expression part

推荐答案

preg_match('/[^\d]+/', $string, $textMatch);
preg_match('/\d+/', $string, $numMatch);

$text = $textMatch[0];
$num = $numMatch[0];


或者,您可以将preg_match_all与捕获组配合使用,一次完成所有操作:


Alternatively, you can use preg_match_all with capture groups to do it all in one shot:

preg_match_all('/^([^\d]+)(\d+)/', $string, $match);

$text = $match[1][0];
$num = $match[2][0];

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

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