Reputation: 441
Following is the String that holds the contact info. This string is dynamic i.e. sometimes new fields eg: mobile number may add up or old fields say: tel number may delete.
<?php $str =
"tel: (123) 123-4567
fax : (234) 127-1234
email : [email protected]";
$newStr = explode(':', $str);
echo '<pre>'; print_r($newStr);
?>
Output of the code is:
Array
(
[0] => tel
[1] => (123) 123-4567
fax
[2] => (234) 127-1234
email
[3] => [email protected]
)
But the output needed is in the following format:
Array
(
[tel] => (123) 123-4567
[fax] => (234) 127-1234
[email] => [email protected]
)
I tried exploding it in may ways... but didn't work. please guide.
Upvotes: 0
Views: 135
Reputation: 20873
Here's a shorter way with regular expressions.
preg_match_all('/(\w+)\s*:\s*(.*)/', $str, $matches);
$newStr = array_combine($matches[1], $matches[2]);
print_r($newStr);
Results:
Array
(
[tel] => (123) 123-4567
[fax] => (234) 127-1234
[email] => [email protected]
)
This example assumes, however, that each data pair is on a separate line as in your provided string and that the "key" contains no spaces.
Upvotes: 2
Reputation: 1355
$str =
"tel: (123) 123-4567
fax : (234) 127-1234
email : [email protected]";
$array = array();
foreach (preg_split('~([\r]?[\n])~', $str) as $row)
{
$rowItems = explode(':', $row);
if (count($rowItems) === 2)
$array[trim($rowItems[0])] = trim($rowItems[1]);
}
You have to use preg_split because there could be different line-ending on each system. There is also possibility that the string is invalid so you should handle that (condition in the foreach cycle)
Upvotes: 0
Reputation: 15616
$txt =
"tel: (123) 123-4567
fax : (234) 127-1234
email : [email protected]";
$arr = array();
$lines = explode("\n",$txt);
foreach($lines as $line){
$keys = explode(":",$line);
$key = trim($keys[0]);
$item = trim($keys[1]);
$arr[$key] = $item;
}
print_r($arr);
Upvotes: 6
Reputation: 2166
use preg_split with the delimeter ":" and "\n" (newline character):
$newStr = preg_split("\n|:", $str);
Upvotes: 0
Reputation: 2418
<?php
$str =
"tel: (123) 123-4567
fax : (234) 127-1234
email : [email protected]";
$contacts = array();
$rows = explode("\n", $str);
foreach($rows as $row) {
list($type, $val) = explode(':', $row);
$contacts[trim($type)] = trim($val);
}
var_export($contacts);
returns
array (
'tel' => '(123) 123-4567',
'fax' => '(234) 127-1234',
'email' => '[email protected]',
)
Upvotes: 0