用数组中的值替换所有出现的字符串 [英] Replacing all occurrences of a string with values from an array

查看:25
本文介绍了用数组中的值替换所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am parsing a string before sending it to a DB. I want to go over all <br> in that string and replace them with unique numbers that I get from an array followed by a newLine.

例如:

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

my function would return 
"Line 1 
 Line 2 
 Line 3 
 Line 4 
"

听起来很简单.我只会做一个while循环,使用strpos获取<br>的所有出现,并使用str_replace将它们替换为所需的数字+ .

Sounds simple enough. I would just do a while loop, get all the occurances of <br> using strpos, and replace those with the required numbers+ using str_replace.

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

Problem is that I always get an error and I have no idea what I am doing wrong? Probably a dumb mistake, but still annoying.

这是我的代码

$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] . ' ' .'
', $str); //str_replace, replaces the first occurance of <br> it finds
    index++;
}

有什么想法吗?

提前致谢,

推荐答案

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

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 

这篇关于用数组中的值替换所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆