【发布时间】:2013-04-15 15:50:51
【问题描述】:
我在将字符串发送到数据库之前对其进行解析。我想遍历该字符串中的所有 <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"
听起来很简单。我只会做一个while循环,使用strpos获取<br>的所有出现,然后使用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++;
}
有什么想法吗?
提前致谢,
【问题讨论】:
-
首先,在第一次迭代中,您将替换
<br>... 的所有实例。要这样做,您只需使用substr_replace替换字符串的一部分这使您可以定义替换的位置。
标签: php string loops phpmyadmin