更新时间:2023-11-07 10:08:40
我会使用正则表达式和自定义回调,如下所示:
I would use a regex and a custom callback, like this:
$str = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$str = preg_replace_callback( '/<br>/', function( $match) use( &$replace) {
return array_shift( $replace) . ' ' . "
";
}, $str);
请注意,这里假设我们可以修改 $replace
数组.如果不是这种情况,您可以保留一个计数器:
Note that this assumes we can modify the $replace
array. If that's not the case, you can keep a counter:
$str = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$count = 0;
$str = preg_replace_callback( '/<br>/', function( $match) use( $replace, &$count) {
return $replace[$count++] . ' ' . "
";
}, $str);
你可以从这个演示看到它输出:
Line 1 Line 2 Line 3 Line 4