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?
Separating a string (by letters and numbers)
Moderator: General Moderators
Re: Separating a string (by letters and numbers)
I can highly recommend to get to know your way around in the wonderful world of Regular Expressions.
PS. This assumes that 'any' in your description can also be zero (otherwise change the two * chars into + in that gibberish on line 3).
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'
}
?>Re: Separating a string (by letters and numbers)
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!
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!