我有这种格式的字符串
{value=very big +$5},{value=super big +$10},{value=extra big +$15}
如何以这种格式将它们转换为2个数组?
例如:
$name=["very big","super big","extra big"];
$price=["5","10","15"]; // OR $price=[5,10,15];
如果字符串格式采用更简单的格式,我可以使用 explode()来实现。但是,这种格式太复杂了。谁知道怎么做?
答案 0 :(得分:1)
将explode与',' ,'=' ,'+$'
$string = "{value=very big +$5},{value=super big +$10},{value=extra big +$15}";
$temp_array = (explode(",",$string));
foreach($temp_array as $val)
{
$temp_array = (explode("=",$val));
$temp_string = $temp_array[1];
$temp_string = str_replace("}","",$temp_string);
$temp_array = (explode("+$",$temp_string));
$name[] = $temp_array[0];
$price[] = $temp_array[1];
}
<强> DEMO 强>
答案 1 :(得分:1)
您可以尝试下面的代码段建议。 Quick-Test: Here.
<?php
$string = '{value=very big +$5},{value=super big +$10},{value=extra big +$15}';
$arrParts = explode(',', $string);
$name = [];
$price = [];
$result = [];
foreach($arrParts as $iKey=>$part){
$block = preg_replace(["#^\{.*?=#", "#\}$#"], "", $part);
$segments = preg_split("#\s#", $block); //<== CREATE AN ARRAY WITH 3 COLUMNS
list($val1, $val2, $val3) = $segments;
$namePart = $val1 . " {$val2}";
$pricePart = preg_replace("#[\+\-\$]#", "",$val3);
$name[] = $namePart;
$price[] = $pricePart;
// BONUS: JUST CREATE A 3RD ARRAY WITH NAMED-KEY
$result[$namePart] = $pricePart;
}
var_dump($name);
//YIELDS::
array (size=3)
0 => string 'very big' (length=8)
1 => string 'super big' (length=9)
2 => string 'extra big' (length=9)
var_dump($price);
//YIELDS::
array (size=3)
0 => string '5' (length=1)
1 => string '10' (length=2)
2 => string '15' (length=2)
var_dump($result);
//YIELDS::
array (size=3)
'very big' => string '5' (length=1)
'super big' => string '10' (length=2)
'extra big' => string '15' (length=2)
答案 2 :(得分:0)
你可以使用正则表达式,例如这应该有效:
preg_match_all('/value=([\w\s]+)\s\+/', $string, $matches)
preg_match_all('/\$([\d]+)\}/', $string, $matches)