String parsing and Array sorting
| From: | Geoff Hankerson | Date: | Mon, 05 Aug 2002 16:32:11 +0000 |
| Subject: | String parsing and Array sorting | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-111225@lists.php.net to get a copy of this message | ||
I am having trouble conceptualizing a solution to a fairly complicated (for
me) string parsing exercise.
The problem is I need to work with "fields" in a text string which is
essentially a profile of a professional person (doctor, lawyer , etc...)
So say the profile is this:
John Doe the best in the world.
Education: School of hard Knocks 2000
Admitted: 2001.
Employment History: John Doe Inc, 2000- present
Professional Associations: PTA
Representative Clients: My dog
Obviously this is a simplified, ficticious example. This profile will come
from a database but here I'l just stuff it in a string variable for
simplicity.
$bio = "Me \n Education: School of hard Knocks 2000. \n Admitted: 2001. \n
Employment History: none \n Professional Associations: PTA \n Representative
Clients: My dog";
The "delimiters" of the text field can be put into an array as follows:
$keywords[0]="Education:";
$keywords[1]="Admitted:";
$keywords[2]="Employment History:";
$keywords[3]="Professional Associations:";
$keywords[4]="Representative Clients:";
$keywords[5]="Community Involvement:";
$keywords[6]="Firm:";
Now I can loop through the text field ($bio) looking for each keyword and
its position and add it to another array
as follows:
$i=0;
$j=-1;
for ($i=0;$i<=count($keywords);$i++) {
$keypos = strpos($bio, $keywords[$i]);
if (!$keypos === false )
{
$j++;
$biofields[$j][0] = $keypos;
$biofields[$j][1] = $keywords[$j];
}
}
I can now output this and get this (in position keyword format):
3 Education:
45 Admitted:
66 Employment History:
93 Professional Associations:
126 Representative Clients:
With this information I can parse through the "bio" and get each "field" if
they are always in the same, static order, but in reality this is not the
case. So I need to sort the array somehow or use some other method to make
this flexible enough to account for any order of "keyword delimiters".
Suggestions?