I tried to split value from string. How to do it in php?
$data = “1-2021, 2-2018, 3-2022”;
Output should be,
var1= “1,2,3”
var2 = “2018,2022,2022”
I tried to split value from string. How to do it in php?
$data = “1-2021, 2-2018, 3-2022”;
Output should be,
var1= “1,2,3”
var2 = “2018,2022,2022”
I’d use explode()
to put it in an array, then spin through that array and use explode on each element breaking on the -
to get the 2 elements, and then add each one to separate $var1Array
and $var2Array
. Finally, I’d use implode()
on each of those arrays to create $var1
and$var2
.
There may be easier ways to do it but off the top of my head I can see how that would work.
Cheers!
=C=
hi, there is a better way to do that with preg_match_all()
<?php
$str = "1-2021, 2-2018, 3-2022, 12-2022";
$exp = "/([0-9]{1,2})-{1}([0-9]{4})/";
preg_match_all($exp, $str, $matches);
$var1 = join(",", $matches[1]);
$var2 = join(",", $matches[2]);
echo "var1 = {$var1}\n";
echo "var2 = {$var2}\n";