0

How can I explode this?

[email protected],123,12,1|[email protected],321,32,2

the output should be:

$email = [email protected]
$score = 123
$street = 12
$rank = 1

then remove the |

$email = [email protected]
$score = 321
$street = 32
$rank = 2

$string = [email protected],123,12,1|[email protected],321,32,2
explode( ',', $string );

is that correct?

7 Answers 7

2
 foreach(explode('|', $str) as $v){
     $data = explode(',',$v);
     echo '$email = '.$data[0].
     '$score = '.$data[1].
     '$street = '.$data[2].
     '$rank = '.$data[3];
 }
Sign up to request clarification or add additional context in comments.

1 Comment

For a known/unchanging/small number of data pieces, it would be cleaner and less error-prone to use list() (e.g. list($email, $score, $street, $rank) = explode(',', $v);)
1

You might want to use strtok() rather than explode().

http://www.php.net/manual/en/function.strtok.php

Comments

1
$arr = preg_split( '"[,|]"', '[email protected],123,12,1|[email protected],321,32,2' );
$len = count($arr);
for( $i = 0; $i < $len; $i+=4 ) {
    $email = $arr[$i];
    $score = $arr[$i+1];
    $street = $arr[$i+2];
    $rank = $arr[$i+3];
}

1 Comment

how can i print this without the array?
0

you need to store the new array in variable >

$arr = explode(',',$string);

and I dont get what you want to do with the second part (after the |), but you can get the first par by doing this > $half = explode('|',$string)[0];

Comments

0

You need to unravel it in the right order:

  • first the blocks separated by |

  • then individual cells separated by ,

A concise way to do so is:

$array = array_map("str_getcsv", explode("|", $data));

Will give you a 2D array.

Comments

0

Use strtok and explode.

$tok = strtok($string, "|");

while ($tok !== false) {
    list($email, $score, $street, $rank) = explode(',', $tok);
    $tok = strtok(",");
}

Comments

0

I think what you want is something like this

   $output = array();

foreach (explode('|', $string) as $person) {
    $output[] = array(
        'email'   =>    $person[0],
        'score'   =>    $person[1],
        'street'  =>    $person[2],
        'rank'    =>    $person[3]
    )
}

This stores all the results in a multidimensional array. For example, to print person 1's email, you'd use

echo $output[0]['email'];   // [email protected]

and to access person 2's street, you'd use

echo $output[1]['street'];   // 32

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.