逐个替换字符串中出现的元素并添加索引
Replacing occurrencies of element inside a string one by one adding an index
我实际上需要用“hello”替换字符串中每次出现的 □□□ 以及每次出现时递增的索引。
$text = "abc □□□ def □□□ ghi □□□";
$pattern = "/□□□/i";
$regex = preg_replace($pattern, "hello", $text);
使用此代码,$regex 将如下所示:
"abc hello def hello ghi hello"
我想要的是让它看起来像这样:
"abc hello1 def hello2 ghi hello3"
我怎样才能做到这一点?
是否可以逐个替换每个出现的位置,以便我可以将这部分代码插入到 for 循环中并向替换字符串添加索引?
您可以使用 preg_replace_callback
并将计数器传递给用作替换参数的匿名函数:
$text = "abc □□□ def □□□ ghi □□□";
$pattern = "/□□□/i";
$counter = 1;
echo preg_replace_callback($pattern, function($m) use (&$counter) {
return "hello" . $counter++;
}, $text);
// => abc hello1 def hello2 ghi hello3
参见PHP demo。
请注意 $counter
前面的 &
可以在替换中更新此变量值。
我实际上需要用“hello”替换字符串中每次出现的 □□□ 以及每次出现时递增的索引。
$text = "abc □□□ def □□□ ghi □□□";
$pattern = "/□□□/i";
$regex = preg_replace($pattern, "hello", $text);
使用此代码,$regex 将如下所示:
"abc hello def hello ghi hello"
我想要的是让它看起来像这样:
"abc hello1 def hello2 ghi hello3"
我怎样才能做到这一点?
是否可以逐个替换每个出现的位置,以便我可以将这部分代码插入到 for 循环中并向替换字符串添加索引?
您可以使用 preg_replace_callback
并将计数器传递给用作替换参数的匿名函数:
$text = "abc □□□ def □□□ ghi □□□";
$pattern = "/□□□/i";
$counter = 1;
echo preg_replace_callback($pattern, function($m) use (&$counter) {
return "hello" . $counter++;
}, $text);
// => abc hello1 def hello2 ghi hello3
参见PHP demo。
请注意 $counter
前面的 &
可以在替换中更新此变量值。