Parsing the comma-separated, then x
-delimited sets of data into separate arrays with integer-typed values can be direct achieved by iterating over a comma-exploded array, then making sscanf()
calls with %d
placeholders
For other scenarios, use %f
for floats, %s
to greedily match consecutive visible characters, and [^,]
, [^x]
, etc to match continuous characters not in the list.
Code: (Demo)
$one = [];
$two = [];
foreach (explode(',', $str) as $set) {
sscanf($set, '%dx%d', $one[], $two[]);
}
var_dump($one, $two);
Output with int
typed values:
array(3) {
[0] => int(20)
[1] => int(24)
[2] => int(40)
}
array(3) {
[0] => int(9999)
[1] => int(65)
[2] => int(5)
}
Extending the sample data format to have values which contain delimiting characters, str_getcsv()
can be rather handy. Consider the following parse&split approach to preserve the double quoted substring -- which is the natural syntax that a .csv file would use.
Code: (Demo)
$str = '"20x9,999",24x65,40x5';
// ^------------------ don't split on this comma and omit the double quotes
$one = [];
$two = [];
foreach (str_getcsv($str) as $set) {
[$one[], $two[]] = explode('x', $set);
}
var_dump($one, $two);
Choose a combination of these techniques depending on your input and desired output for real world tasks where nested splitting is needed.