使用分隔符将字符串分解为特定数据并存储在 PHP 中的数组中

我有以下文本字符串

Liane Lanford$310.40$0.00$325.92 Ken Christenson$134.75$0.00$141.49 Melissa Jaramillo$951.78$0.00$999.37

我需要创建一个数组,以便我可以按照以下格式将数据插入 mysql 数据库

http://img.mukewang.com/62d271f20001633003790121.jpg

我尝试使用explode但堆叠在Ken Christensonand来做到这一点Melissa Jaramillo。复杂性是可能有 3、4 五个或更多客户而不是 3。我如何在 php 中做到这一点。



largeQ
浏览 135回答 1
1回答

四季花海

你可以用正则表达式拆分它:preg_match_all('/ ?([^\$]+)(\$[0-9\.,]+)(\$[0-9\.,]+)(\$[0-9\.,]+)/i',$str,$results);该$results数组将包含索引 0 处的完整匹配项,后跟名称、小计、保留、总计:[&nbsp; [&nbsp; &nbsp; "Liane Lanford$310.40$0.00$325.92",&nbsp; &nbsp; " Ken Christenson$134.75$0.00$141.49",&nbsp; &nbsp; " Melissa Jaramillo$951.78$0.00$999.37"&nbsp; ],&nbsp; [&nbsp; &nbsp; "Liane Lanford",&nbsp; &nbsp; "Ken Christenson",&nbsp; &nbsp; "Melissa Jaramillo"&nbsp; ],&nbsp; [&nbsp; &nbsp; "$310.40",&nbsp; &nbsp; "$134.75",&nbsp; &nbsp; "$951.78"&nbsp; ],&nbsp; [&nbsp; &nbsp; "$0.00",&nbsp; &nbsp; "$0.00",&nbsp; &nbsp; "$0.00"&nbsp; ],&nbsp; [&nbsp; &nbsp; "$325.92",&nbsp; &nbsp; "$141.49",&nbsp; &nbsp; "$999.37"&nbsp; ]]对于插入部分(您在评论中询问),试试这个:试试这个:for ($i=0;$i<count($array[0]);$i++) {&nbsp; &nbsp; mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('" . $array[0][$i] . "','" . $array[1][$i] . "','" . $array[2][$i] . "','" . $array[3][$i] . "') ");}但请记住,应该检查和转义这些值。如果任何名称包含 ' ,则查询将失败
打开App,查看更多内容
随时随地看视频慕课网APP