Sanj Sanj - 1 year ago 70
PHP Question

Textarea lines to array using php

I have a php variable that contain value of textarea as below.

Name:Jay
Email:[email protected]
Contact:9876541230


Now I want this lines to in array as below.

Array
(
[Name] =>Jay
[Email] =>[email protected]
[Contact] =>9876541230
)


I tried below,but won't worked:-

$test=explode("<br />", $text);
print_r($test);

Answer Source

you can try this code using php built in PHP_EOL but there is little problem about array index so i am fixed it

<?php
$text = 'Name:Jay
Email:[email protected]
Contact:9876541230';
$array_data = explode(PHP_EOL, $text);

$final_data = array();
foreach ($array_data as $data){
    $format_data = explode(':',$data);
    $final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);

and output is :

Array
(
    [Name] => Jay
    [Email] => [email protected]
    [Contact] => 9876541230
)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download