Issue
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.
For example:
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"
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+\n 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.
Here is my code
$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++;
}
Any ideas please?
Thanks in advance,
Solution
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) . ' ' . "\n";
}, $str);
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++] . ' ' . "\n";
}, $str);
You can see from this demo that this outputs:
Line 1 Line 2 Line 3 Line 4
Answered By - nickb
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.