Split String into Text and Number

user1981823 picture user1981823 · Jan 15, 2013 · Viewed 10.2k times · Source

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

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

Anything after the number can be discarded

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

Answer

Joseph Silber picture Joseph Silber · Jan 15, 2013
preg_match('/[^\d]+/', $string, $textMatch);
preg_match('/\d+/', $string, $numMatch);

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

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];