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
Quesion to string parsing
Moderator: General Moderators
-
visionmaster
- Forum Contributor
- Posts: 139
- Joined: Wed Jul 14, 2004 4:06 am
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];
}Untested....
Should output....
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);
?>Code: Select all
Array
(
[Name] => 1
[Company Name] => 2
[Street] => 3
[City] => 4Code: Select all
=> 5
[Country] => 6
[Tel] => 7
)-
visionmaster
- Forum Contributor
- Posts: 139
- Joined: Wed Jul 14, 2004 4:06 am