gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:45:25 24 4
gpt4 key购买 nike

我在将字符串发送到数据库之前对其进行解析。我想遍历所有 <br>在该字符串中,并将它们替换为我从数组中获得的唯一数字,后跟换行符。

例如:

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"

听起来很简单。我会做一个 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++;
}

有什么想法吗?

提前致谢

最佳答案

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

$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);

请注意,这假设我们可以修改 $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);

this demo可以看出这输出:

Line 1 Line 2 Line 3 Line 4 

关于php - 用数组中的值替换所有出现的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16152283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com