Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number sequence to array in PHP

Kinda of a noobie in PHP and Regex, I receive the following from a web service:

test:002005@1111@333333@;10205@2000@666666@;002005@1111@55555@;

The above line is a sequence of 3 numbers which repeats 3 times. I would like to get the 3rd number of each sequence and I believe the best course (besides 3000 explodes) would be preg_match_all but I am having a tough time wrapping my mind around RegEx.

The end result should look like this:

 Array
    (
        [0] => 333333
        [1] => 666666
        [2] => 55555
    )

Thanks in advance for any help.

like image 987
Xander Avatar asked Mar 28 '26 10:03

Xander


2 Answers

if(preg_match_all('/.*?(?:\d+@){2}(\d+)@;/',$s,$m)) {
        print_r($m[1]);
}

http://ideone.com/99M9t

or

You can do it using explode as:

$input = rtrim($input,';');
$temp1 = explode(';',$input);
foreach($temp1 as $val1) {
        $temp2 = explode('@',$val1);
        $result[] = $temp2[2];
}
print_r($result);

http://ideone.com/VH29g

like image 77
codaddict Avatar answered Mar 30 '26 03:03

codaddict


Use the function explode()

<?php

$pizza  = "piece1@piece2@piece3@piece4@piece5@piece6";
$pieces = explode("@", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

?>
like image 37
Ron van der Heijden Avatar answered Mar 30 '26 01:03

Ron van der Heijden