tags:

views:

62

answers:

4

hi

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 item per line.

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

thnx

A: 

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...
}
Jon Benedicto
thx it seems great, but what if user didnt type $info or comma(he typed just $data) in a line, will $info be empty?
Ahmet vardar
A: 
$x='data1, data1info
data2, data2info
data3, data3info';

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

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)
Pascal MARTIN
A: 

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

Scott Evernden