I have an array of strings. I am trying to extract the data in the parentheses, ( and ), from each string. The problem is that it does not extract the data in the middle from the first element, if there is nothing else in front of it.
This is the code snippet with an indication of the needed/captured values:
<?php
$data = [
'aaa|45.85[u]52.22 - 43.75 - 36.5[d]25.75',
// #1^^^ #2^^^^^ #3^^^^^ #4^^^^^
'bbb|238.4[u]345.45 - 24.1[d]13.85 - 56.4[d]56'
// #1^^^ #2^^^^^^ #3^^^^^ #4^^
];
$new = [];
foreach ($data as $element)
{
preg_match("#^(.*?)\|[\w\[\.]+\]?(.*?) - [\w\[\.]+\]?(.*?) - [\w\[\.]+\]?(.*?)$#", $element, $match);
$string = $match[1];
$num1 = $match[2];
$num2 = $match[3];
$num3 = $match[4];
$new[$string] = [
'num1' => $num1,
'num2' => $num2,
'num3' => $num3,
];
}
print_r($new);
?>
The code above should gives me this result:
$new = [
'aaa' => [
'num1' => '52.22',
'num2' => '43.75',
'num3' => '25.75',
],
'bbb' => [
'num1' => '345.45',
'num2' => '13.85',
'num3' => '56',
]
];
But it gives me this:
$new = [
'aaa' => [
'num1' => '52.22',
'num2' => '',
'num3' => '25.75',
],
'bbb' => [
'num1' => '345.45',
'num2' => '13.85',
'num3' => '56',
]
];
[\w\[\.]+characters before the bracket, in the first case, there isn't one so it's not matching. Changing+to*may help if that is in fact a valid match