How do I Split an alphanumeric string into array?

Hi,

I have the following string = “Mr Brown 40 Jones 21 Smith 18”

How do I split the string into Name and Numbers , like this

$person[0]=“Mr Brown”
$numbers[0]=“40”
$person[1]=“Jones”
$numbers[1]=“21”
$person[2]=“Smith”
$numbers[2]=“18”

Thanks

Hi,
Try use this code:

$string = "Mr Brown 40 Jones 21 Smith 18";
$person = $numbers = array();

if(preg_match_all('/([a-z ]+[0-9]+)/i', $string, $mt)) {
  $nrmt = count($mt[0]);
  for($i=0; $i<$nrmt; $i++) {
    if(preg_match('/([a-z ]+)([0-9]+)/i', $mt[0][$i], $mt2)) {
      $person[$i] = trim($mt2[1]);
      $numbers[$i] = $mt2[2];
    }
  }
}
else echo 'Not matche';

// test

echo '<pre>';
var_export($person);
var_export($numbers);
echo '</pre>';

wow, thanks for the quick response… it seems to work perfectly…

Just going back to my first post, I have another problem I’m not sure if its possible to work around - the above code works great with string like this “Mr Brown 40 Jones 21 Smith 18” but sometimes the string dos not have numbers in it, for example string = “Mr Brown Jones 21” this causes the above code to stop working.

Would it be possible to have a failsafe which adds the value “na” to the $numbers[i] string if number are missing from the string?

Thanks

How does the script know where numbers belong?

“Mr Brown Jones 21 Simon 48”

Should it put out
Mr na Brown Jones 21 Simon 48?
What about
Mr Brown na Jone 21 Simon 48
or
Mr na Brown na Jones 21 Simon 48?

I would like itto put out if possible - Mr Brown na Jone 21 Simon 48 if the string is missing numbers

My point is, how can the script know where the numbers are missing?

“Mr Brown Jones” may be a valid name.

It might shed some light if you explained where the string was originally coming from.

They are being pulled a mysql table from a database table, but as the above post mentioned I don’t think it may be possible to do what I want

So are you really saying the whole string is stored as one single column from the table?

ie “select mystring from mytable where id = 1”


mytable
=====
id | mystring
 1 | "Mr Brown 40 Jones 21 Smith 18"

If so, then how did it get into your database?

Where did it originate from?

Yes correct, all in one string

It the data was originally pulled in from a spreadsheet

So … did the spreadsheet have all these values in one singe cell?

And if they didn’t, why didn’t you just export it as a CSV and import it into separate columns?