我正在尝试使用 PHP 来替换一段 JSON 中的一些项目 ID,并且遇到一个问题,即第一遍的替换被第二遍的替换覆盖。
<?php
$body = "Hello World";
$soul = str_replace(['World', 'Earth'], ['Earth', 'Vietnam'], $body);
echo $soul;
预期:“Hello Earth”观察到“Hello Vietnam”
我的情况比较无情,因为我的映射是数字到数字,比如“id139”=>“id189”和“id189”=>“id18”。我如何在一大堆文本中进行搜索和替换而不冒多次替换的风险?
我们最接近好的解决方案是这样的:
$regPatterns = [
"/floatingSectionItems-(\d+)-1006/",
"/floatingSectionItems-(\d+)-160/",
"/floatingSectionItems-(\d+)-1/",
];
$regReplacements = [
"goosebumps-160-160",
"goosebumps-168-168",
"goosebumps-171-171",
];
$layout = preg_replace($regPatterns, $regReplacements, $layout);
$layout = str_replace(‘goosebumps’, ‘floatingSectionItems’, $layout);
虽然这个 works 在这种特殊情况下,我觉得可能有不需要五遍的解决方案;就像一个 preg_match_all() 后跟一个有限的 str_replace() 或一种解析原始文件并一次性替换的方法。
我认为你可能需要尝试弄清楚如何构建一个单一的模式正则表达式,它可以潜在地工作带有回调你的自定义替换逻辑,这样模式就不会在以前的替换中被处理。
$layout = " blah blah floatingSectionItems-100-200 floatingSectionItems-300-400 blah blah ";
$layout = preg_replace_callback('/floatingSectionItems-(\d+)-(\d+)/', function($matches){
if( $matches[1] == '100' and $matches[2] == '200' )
{
return 'floatingSectionItems-300-400';
}
if( $matches[1] == '300' and $matches[2] == '400' )
{
return 'floatingSectionItems-100-200';
}
return $matches[0];
}, $layout);
echo $layout;
然后您可以在回调中构建您的替换逻辑,在这个例子中我翻转了两个数字模式。