PHP如何逐个替换字符串占位符并为每处匹配添加递增索引
PHP实现占位符按匹配顺序替换为带递增索引的内容
现有写法的问题是preg_replace全局替换时会将所有匹配项替换为固定值,无法自动附加递增索引,有两种实现方案:
方案1:使用preg_replace_callback(推荐)
直接通过正则替换回调处理计数逻辑,代码最简:
$text = "abc □□□ def □□□ ghi □□□"; $pattern = "/□□□/i"; $index = 1; // 自定义索引起始值 $result = preg_replace_callback($pattern, function($matches) use (&$index) { return "hello" . $index++; }, $text); // 输出:abc hello1 def hello2 ghi hello3 echo $result;
注意:计数器$index需要通过引用&传递到回调函数中,否则每次回调都会读取初始值,无法实现递增
方案2:自定义循环逐个替换
如果需要嵌入额外的自定义逻辑到替换流程中,可以先匹配所有占位符位置再循环替换:
$text = "abc □□□ def □□□ ghi □□□"; $pattern = "/□□□/i"; // 获取所有匹配项的偏移位置 preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE); $offsetFix = 0; // 修正替换后长度变化带来的位置偏移 foreach ($matches[0] as $key => $matchItem) { $replaceStr = "hello" . ($key + 1); $originLength = strlen($matchItem[0]); $replaceLength = strlen($replaceStr); $text = substr_replace($text, $replaceStr, $matchItem[1] + $offsetFix, $originLength); $offsetFix += $replaceLength - $originLength; } // 输出:abc hello1 def hello2 ghi hello3 echo $text;
内容的提问来源于stack exchange,提问作者abh3698
相关产品推荐
相关产品推荐

