我有一个现有数组的值,如下所示:
Product One (Amount: 199.99 USD, Select Option: Option One, Product One (CRM): 1)
我想要摆脱的是一个看起来像这样的数组:
Product One
Amount: 199.99 USD
Select Option: Option One
Product One (CRM): 1
我尝试的是:
$product_arr = json_decode($product_details[0]);
$prod_arr_add = preg_split('/[\,(]+/', $product_arr[0]);
print_r ($prod_arr_add);
看起来像:
Array
(
[0] => Product One
[1] => Amount: 199.99 USD
[2] => Select Option: Option One
[3] => Product One
[4] => CRM): 1)
)
其他尝试与我尝试过的差异未能同样产生预期结果。
如何将文本字符串拆分为数组?
答案 0 :(得分:0)
只有一个样本字符串需要测试,我做了一些假设并牺牲了正则表达式模式的效率。如果需要加强此解决方案,请评论和/或编辑您的问题。
$regex="/^(.+?)\s\((.*?),\s(.*?),\s(.*)\)$/";
$string="Product One (Amount: 199.99 USD, Select Option: Option One, Product One (CRM): 1)";
if(preg_match($regex,$string,$matches)){
$prod_arr_add=array_slice($matches,1); // remove first element from the array (fullmatch)
echo "<pre>";
var_export($prod_arr_add);
echo "</pre>";
}else{
echo "no match";
}
输出:
array (
0 => 'Product One',
1 => 'Amount: 199.99 USD',
2 => 'Select Option: Option One',
3 => 'Product One (CRM): 1'
)
正则表达式:
^(.+?)\s\( #Capture everything from the start to a space followed by a opening parenthesis
(.*?),\s #Capture everything before a comma followed by a space
(.*?),\s #Capture everything before a comma followed by a space
(.*)\)$ #Capture everything before a closing parenthesis at the end of the string