用数组中的值替换所有出现的字符串

r3x*_*r3x 5 php string loops phpmyadmin

我在将字符串发送到数据库之前解析它.我想要查看<br>该字符串中的所有字符串并将其替换为我从数组后跟newLine获取的唯一数字.

例如:

str = "Line <br> Line <br> Line <br> Line <br>"
$replace = array("1", "2", "3", "4");

my function would return 
"Line 1 \n Line 2 \n Line 3 \n Line 4 \n"
Run Code Online (Sandbox Code Playgroud)

听起来很简单.我只是做一个while循环,得到<br>使用strpos的所有出现,并使用str_replace替换那些具有所需数字+ \n的那些.

问题是我总是遇到错误,我不知道我做错了什么?可能是一个愚蠢的错误,但仍然很烦人.

这是我的代码

$str     = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$replaceIndex = 0;

while(strpos($str, '<br>') != false )
{
    $str = str_replace('<br>', $replace[index] . ' ' .'\n', $str); //str_replace, replaces the first occurance of <br> it finds
    index++;
}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

提前致谢,

nic*_*ckb 8

我会使用正则表达式和自定义回调,如下所示:

$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) . ' ' . "\n";
}, $str);
Run Code Online (Sandbox Code Playgroud)

请注意,这假设我们可以修改$replace数组.如果不是这样,你可以保留一个柜台:

$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++] . ' ' . "\n";
}, $str);
Run Code Online (Sandbox Code Playgroud)

您可以从此演示中看到此输出:

Line 1 Line 2 Line 3 Line 4 
Run Code Online (Sandbox Code Playgroud)