Quesion to string parsing

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
visionmaster
Forum Contributor
Posts: 139
Joined: Wed Jul 14, 2004 4:06 am

Quesion to string parsing

Post by visionmaster »

Hello,

String I:
---------
$output=
Name: 1
Company Name: 2
Street: 3
City: 4
Code: 5
Country: 6
Tel: 7

String II:
----------
$output=
Name: 1
Street: 2
City: 3
Code: 4
Country: 5
Fax: 6

=> I want to pick out the data from the strings. Since the information varies, I want an array like this (e.g. for String II):
array["Name"] = 1
array["Street"] = 2
array["City"]=3
...

$array = explode("\n",trim($output)); splits a string by string an returns an array of strings.
So I have e.
array[0]=Name: 1
array[1]=Street: 2
array[2]=City: 3

==>Question, how do I pick out each element of the array and make an associative array out of it?

Thanks,
visionmaster
User avatar
liljester
Forum Contributor
Posts: 400
Joined: Tue May 20, 2003 4:49 pm

Post by liljester »

do another explode on each array element.

Code: Select all

$big_array = explode("\n", trim($output));
for($i = 0; $i < count($big_array); $i++){
   $small_array = explode(":", trim($big_array[$i]));
   $info_array[$small_array[0]] = $small_array[1];
}
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Untested....

Code: Select all

<?php
$output = '
Name: 1
Company Name: 2
Street: 3
City: 4
Code: 5
Country: 6
Tel: 7 
';

if (preg_match_all('/^([^:]+):\s+(\d+)/m', trim($output), $matches, PREG_SET_ORDER))
{
  foreach ($matches as $match)
  {
   $array[$match[1]] = $match[2];
  }
}
print_r($array);
?>
Should output....

Code: Select all

Array
(
    [Name] => 1
    [Company Name] => 2
    [Street] => 3
    [City] => 4

Code: Select all

=> 5
    [Country] => 6
    [Tel] => 7
)
visionmaster
Forum Contributor
Posts: 139
Joined: Wed Jul 14, 2004 4:06 am

Post by visionmaster »

Wow, thanks! That's the solution. I already had the idea, but didn't know how to realize it.

Thanks!!!
Post Reply