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
| SitePoint Sponsor |
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:
PHP 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>';
Free: Web Programming Courses HTML, CSS, Flash
Web Programming: AJAX Course and PHP-MySQL Course video Lessons
Good JavaScript and jQuery course for beginners
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?
Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.
My point is, how can the script know where the numbers are missing?
"Mr Brown Jones" may be a valid name.
Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.

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

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"
If so, then how did it get into your database?Code:mytable ===== id | mystring 1 | "Mr Brown 40 Jones 21 Smith 18"
Where did it originate from?

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


Bookmarks