Как создать подходящее регулярное выражение?
Есть такие строки:
text 16.11 19.22 21.33
text 17.11 23.22 25.33 27.55
text 18.11 26.22
нужно чтобы получилось так:
array('test'=>'text', 'prices'=>[16.11, 19.22, 21.33]);
array('test'=>'text', 'prices'=>[17.11, 23.22, 25.33, 27.55]);
array('test'=>'text', 'prices'=>[18.11, 26.22]);
создал что-то похожее, но не совсем подходит:
\$arr[]=array('test'=>'$1','prices'=>[$2]);
Как правильно создать регулярное выражение?
Количество цен может быть разное в ряду
P.S.
([a-zA-Z]*)\s*(([0-9\.]+))+
=> array('test'=>'$1','prices'=>[$2])\s
получается так:
array('test'=>'text','prices'=>[16.11])sarray('test'=>'','prices'=>[19.22])sarray('test'=>'','prices'=>[21.33])s
array('test'=>'text','prices'=>[17.11])sarray('test'=>'','prices'=>[23.22])sarray('test'=>'','prices'=>[25.33])sarray('test'=>'','prices'=>[27.55])s
array('test'=>'text','prices'=>[18.11])sarray('test'=>'','prices'=>[26.22])s
$str = "
text 16.11 19.22 21.33
text 17.11 23.22 25.33 27.55
text 18.11 26.22
";
preg_match_all('/^(\D+)([\d+\.\s]+)$/im', $str, $matches);
$res = [];
foreach ($matches[1] as $ix => $key) {
$res[$ix]['test'] = trim($key);
$res[$ix]['prices'] = array_map(function($i) {return (float) $i;}, explode(' ', $matches[2][$ix]));
}
var_dump($res);
Решение с тремя explode 3v4l:
echo 'Если количество/вид пробелов жёстко заданы/известны:', PHP_EOL;
$res = [];
$lines = explode("\n", trim($str));
foreach ($lines as $line) {
[$key, $prices] = explode(" ", $line);
$prices = explode(' ', $prices);
$res[] = ['key' => $key, 'prices' => $prices];
}
echo json_encode($res), PHP_EOL;
Решение с preg_split 3v4l:
echo 'Если не завязываться на количестве/виде пробелов: ', PHP_EOL;
$res = [];
$lines = preg_split('#[\n\r]+#', trim($str));
foreach ($lines as $line) {
$prices = preg_split('#\s+#', $line);
$key = array_shift($prices);
$res[] = ['key' => $key, 'prices' => $prices];
}
echo json_encode($res), PHP_EOL;
Для генерации кода в PHPStorm, могу предложить вот такую шутку:
^(\S+)\s+(.*)
=> ['key' => '$1', 'prices' => explode(' ', '$2')]
Оборудование для ресторана: новинки профессиональной кухонной техники
Частный дом престарелых в Киеве: комфорт, забота и профессиональный уход