我有这个字符串:
$string = ["coffee candy (123456789) (Amount: 0.00 EUR)",
"fruity candy (987654332) (Amount: 0.00 EUR)"];
我希望结果如下:
array(2) {
[0] => array {
["name"] => string(12) coffee candy
["num"] => string(9) 123456789
["amount"] => string(15) Amount 0.00 EUR
}
[1] => array {
["name"] => string(12) fruity candy
["num"] => string(9) 987654332
["amount"] => string(15) Amount 0.00 EUR
}
}
或类似的东西。是否可以使用正则表达式?如果是这样,怎么样?
答案 0 :(得分:0)
您可以使用字符(
展开字符串,然后修剪)
,查看live demo
<?php
$string = ["coffee candy (123456789) (Amount: 0.00 EUR)",
"fruity candy (987654332) (Amount: 0.00 EUR)"];
$keys = ['name', 'num', 'amount'];
$array = array_map(function($v) use($keys) {
$arr = explode('(', $v);
$arr = array_map(function($v){
return trim($v, " \t\n\r\0\x0B)");
}, $arr);
return array_combine($keys, $arr);
}, $string);
print_r($array);
答案 1 :(得分:0)
如果输入是一致的(机器生成的)我会删除正则表达式并执行类似的操作
$array = explode(',',$string);
foreach($array as $data){
$parts = explode('(',$data);
$result[]['name'] = trim(substr($parts[0], 1));
$result[]['num'] = trim(substr($parts[1], 0, -1));
$result[]['amount'] = trim(substr($parts[2], 0, -2));
}
但是这只适用于一致的字符串。
答案 2 :(得分:0)
我认为你需要这样的东西
<?php
$text = 'coffee candy (123456789) (Amount: 0.00 EUR)';
preg_match('/^([a-zA-Z\s]+)\s+?\(([\d]+)\)\s+?\((.+)\)/', $text, $matches);
print_r($matches);