开发者

parsing items by line and comma php

i have a textarea on the page. user will type items by lines and comma.

for example,

data1, data1info
data2, data2info
data3, data3info

there are 2 开发者_Python百科item per line.

how can i parse them per line and get items per line individually.

thnx


$x='data1, data1info
data2, data2info
data3, data3info';

foreach(explode("\n",$x) as $line){
    $item=explode(",",$line);
    //echo $item[0].$item[1];
}


Use preg_split to break the lines on the newline character, then again to break the line into the 2 parts.

For example:

$lines = preg_split( "[\r\n]", $_POST[ 'TextArea' ] );
foreach( $lines as $line )
{
    list( $data, $info ) = preg_split( ",\s+", $line, 2 );
    // Use $data and $info...
}


You can use explode to split the string by end of lines, first ; the,, explode those lines again, using ',' as a separator :

$str = <<<STR
data1, data1info
data2, data2info
data3, data3info
STR;

$lines = explode(PHP_EOL, $str);
foreach ($lines as $line) {
    list ($first, $second) = explode(',', $line);
    $first = trim($first);
    $second = trim($second);
    var_dump($first, $second);
}

Note I also used trim to remove any left spaces at the beginning / end of strings.

And you'll get :

string 'data1' (length=5)
string 'data1info' (length=9)
string 'data2' (length=5)
string 'data2info' (length=9)
string 'data3' (length=5)
string 'data3info' (length=9)


you'd use explode() to split by newlines .. then explode() again to split by commas. you'd then probably use array_map(trim, ) on the resultant array(s) to remove any surrounding whitespace

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜