Page 1 of 1

Quesion to string parsing

Posted: Thu Jul 22, 2004 8:21 am
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

Posted: Thu Jul 22, 2004 8:34 am
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];
}

Posted: Thu Jul 22, 2004 9:11 am
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
)

Posted: Thu Jul 22, 2004 9:47 am
by visionmaster
Wow, thanks! That's the solution. I already had the idea, but didn't know how to realize it.

Thanks!!!