当前位置:Gxlcms > PHP教程 > preg_replace_callback替换preg_replace

preg_replace_callback替换preg_replace

时间:2021-07-01 10:21:17 帮助过:17人阅读

$tem = $arr['invoice_type'];
echo "
";  
print_r($tem);
输出
a:2:{s:4:"type";a:3:{i:0;s:8:"个人发票";i:1;s:8:"企业发票";i:2;s:0:"";}s:4:"rate";a:3:{i:0;d:6;i:1;d:6;i:2;d:0;}}

$teem []= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $arr['invoice_type'] );
echo "
";  
print_r($teem);
输出
Array
(
[0] => a:2:{'s:'.strlen('type').':"type";'a:3:{i:0;'s:'.strlen('个人发票').':"个人发票";'i:1;'s:'.strlen('企业发票').':"企业发票";'i:2;'s:'.strlen('').':"";'}'s:'.strlen('rate').':"rate";'a:3:{i:0;d:6;i:1;d:6;i:2;d:0;}}
)

$teemm []= preg_replace_callback('!s:(\d+):"(.*?)";!s', function ($matches) {return strlen('$2').':\"$2\";';}, $arr['invoice_type'] );
echo "
";  
print_r($teemm);
输出
Array
(
[0] => a:2:{2:\"$2\";a:3:{i:0;2:\"$2\";i:1;2:\"$2\";i:2;2:\"$2\";}2:\"$2\";a:3:{i:0;d:6;i:1;d:6;i:2;d:0;}}
)

如何让preg_replace_callback输出的信息和preg_replace输出的一样


回复讨论(解决方案)

不知道你要干什么
实例的结果并不对!

第二个输出弄错了是下面的
$teem []= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $arr['invoice_type'] );
echo "

";  
print_r($teem);
输出
Array
(
[0] => a:2:{s:4:"type";a:3:{i:0;s:8:"个人发票";i:1;s:8:"企业发票";i:2;s:0:"";}s:4:"rate";a:3:{i:0;d:6;i:1;d:6;i:2;d:0;}}
)

不知道你要干什么
实例的结果并不对!



第二个输出弄错了是下面的
$teem []= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $arr['invoice_type'] );
echo "
";  
print_r($teem);
输出
Array
(
[0] => a:2:{s:4:"type";a:3:{i:0;s:8:"个人发票";i:1;s:8:"企业发票";i:2;s:0:"";}s:4:"rate";a:3:{i:0;d:6;i:1;d:6;i:2;d:0;}}
)

$s = preg_replace_callback('/s:\d+:"(.+?)";/s',		function($r) {			$n = strlen($r[1]);			return "s:$n:\"$r[1]\";";		}, $s);

$s = preg_replace_callback('/s:\d+:"(.+?)";/s',		function($r) {			$n = strlen($r[1]);			return "s:$n:\"$r[1]\";";		}, $s);



大神我按照你的改了输出数据是这样
代码
$teem = preg_replace_callback('/s:\d+:"(.+?)";/s',
function($r) {
$n = strlen($r[1]);
return "s:$n:\"$r[1]\";";
}, $arr['invoice_type'] );
echo "
";  
print_r($teem);
输出
a:2:{s:4:"type";a:3:{i:0;s:8:"个人发票";i:1;s:8:"企业发票";i:2;s:12:"";}s:4:"rate";a:3:{i:0;d:6;i:1;d:6;i:2;d:0;}}

企业发票后边S:0:"" 变为了s:12:"" 多了12长度,这个怎么来的

没考虑值为空的情况
把 '/s:\d+:"(.+?)";/s'
改为 '/s:\d+:"(.*?)";/s'

没考虑值为空的情况
把 '/s:\d+:"(.+?)";/s'
改为 '/s:\d+:"(.*?)";/s'



万分感谢

人气教程排行