开发者

How to get comma separated values from the string in php

I have a string $employee="Mr vinay HS,engineer,Bangalore";. i want to store Mr vinay H S in $name ,engineer in $job and Bangalore in $locati开发者_如何学Pythonon. how to do this


$record = explode(",",$employee);
$name = $record[0];
$job = $record[1];
$location = $record[2];


Use the list function to take the exploded array into 3 variables

list($name, $job, $location) = explode(',', $employee);


list($name,$job,$location) = explode(',',$employee);

Note: this will obviously only work if the string is in the format you specified. If you have any extra commas, or too few, then you'll have problems.

It's also worth pointing out that PHP has dedicated functions for handling CSV formatted data.

See the manual page for str_getcsv for more info.

While explode() is the quickest and easiest way to do it, using str_getcsv() rather than simple explode() will allow you to handle input more complex input, eg containing quoted strings, etc.


explode will do just that I guess

http://php.net/manual/en/function.explode.php

Any more help on this would suffer from givemethecode-ism, so I leave you to it ;-)


list($name,$job,$location) = explode(',',$employee);


Something like the following should work:

//The employee name
$employee= "Mr vinay HS,engineer,Bangalore";

//Breaks each portion of the employee's name up
list($name, $job, $location) = explode(',',$employee);

//Outputs the employee's credentials
echo "Name: $name; Job: $job; Location: $location";


Or you can use another function to do that - http://php.net/manual/en/function.str-getcsv.php

list($name,$job,$location) = str_getcsv($employee);


You can look at the explode() and list() functions:

list($name, $job, $location) = explode(",", $employee);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜