Separating a string (by letters and numbers)

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Separating a string (by letters and numbers)

Post by timWebUK »

I've searched high and low on the forum and Google and haven't found an answer so I've resorted to posting on here with an embarrassingly trivial question.

I have a string which will contain an upper case letter, any number of lowercase letters, then any number of tabs/spaces then an integer. I wish to separate this string. First of all I am using trim() to remove the unwanted tabs and spaces. I then wish to take the string (case-sensitive) and store that in one array, then take the integer and store that in a variable for other use...

An example would be:

"Arttsdfsf 678"

To result in:

$theArray = array('Arttsdfsf');
$theVariable = 678;

Any ideas please?
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Separating a string (by letters and numbers)

Post by Apollo »

I can highly recommend to get to know your way around in the wonderful world of Regular Expressions.

Code: Select all

<?php
$s = 'Arttsdfsf 678';
if (!preg_match('/^([A-Z][a-z]*)\s*([0-9]+)$/',$s,$m))
{
	die('Sorry sir, your string does not meet the requirements');
}
else
{
	$a = $m[1]; // $a is now 'Arttsdfsf'
	$b = $m[2]; // $b is now '678'
}
?>
PS. This assumes that 'any' in your description can also be zero (otherwise change the two * chars into + in that gibberish on line 3).
User avatar
timWebUK
Forum Contributor
Posts: 239
Joined: Thu Oct 29, 2009 6:48 am
Location: UK

Re: Separating a string (by letters and numbers)

Post by timWebUK »

Thanks, Apollo.

Yeah I definitely do need to actually learn regular expressions as I do use them quite a lot. I feel like a cheat just using someone else's regex!
Post Reply