Home > Article > Backend Development > preg_replace_callback 问题
$zheng="1";//重复的整合一起($wupin_rs或$wupin_add)$jia="0";//相加($wupin_rs,$wupin_add)$jian="0";//相减($wupin_rs,$wupin_add)$shanchu="0";//把数量为0的删除($wupin_rs)$suan="0";//算总价($wupin_rs)$wupin_rs="";//原有的$wupin_add="";//新添加/删除的//A类别0::::::品名1::::::品牌厂商2::::::规格3::::::单价4::::::单位5::::::数量6::::::总价7::::::重量8$wupin_rs="A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::10::::::0::::::100||||||A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::20::::::0::::::200||||||A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::30::::::0::::::200";if($wupin_rs&&$zheng==1){ $category=""; $morefr=explode('||||||',$wupin_rs); $mfcount=count($morefr); for($mfi=0;$mfi<$mfcount;$mfi++) { $morefrf=explode('::::::',$morefr[$mfi]); $category_tem=$morefr[$mfi]; $so=$morefrf[0].'::::::'.$morefrf[1].'::::::'.$morefrf[2].'::::::'.$morefrf[3].'::::::'.$morefrf[4].'::::::'.$morefrf[5].'::::::'; if($category==""){$category=$category_tem;}//第一次 elseif(stripos($category,$so)>-1&&wupin_run_check($so)===false)//物品“类别”不显示重复类别(每种只显示一次),判断是否含有 { //改数量 $category= preg_replace_callback("/(?<=$so)\d+/is", function ($matches) use($morefrf) { return (int)$matches[0]+(int)$morefrf[6]; } ,$category,1);//只替换一次 } else //如果已有重复,就只统计数量 { $category=$category."||||||".$category_tem;//如果没有重复就加 } } $wupin_rs=$category;}echo $wupin_rs;//物品处理时判断非法字符 function wupin_run_check($zhi) { if(preg_match("/[*?#=]|\/|\[|\]|\\\|\"|\|/",$zhi)) { return true; } else { return false; } }
$wupin_rs="A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::10::::::0::::::100||||||A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::20::::::0::::::200||||||A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::30::::::0::::::200";$pattern = '/(?=^|\|)\|*([^:]+)::::::([^:]+)::::::([^|:]+)::::::([^:]+)::::::([^:]+)::::::([^:]+)::::::([^:]+)::::::([^:]+)::::::([^|]+)/';$res = array();preg_replace_callback($pattern, function($m) use (&$res) { $k = join('::::::', array_slice($m, 1, 6)); $res[$k]['标识'] = $k; @$res[$k]['数量'] += $m[7]; @$res[$k]['总价'] += $m[5] * $m[7]; @$res[$k]['重量'] += $m[9]; }, $wupin_rs);echo join('||||||', array_map(function($t) { return join('::::::', $t); }, $res));
A类别0::::::品名1::::::品牌厂商2::::::规格3::::::1::::::单位5::::::60::::::60::::::500