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,
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
Finally, the new string method string. replaceAll(search, replaceWith) replaces all string occurrences.
Replace an Element in an Array using Array.Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.
splice() method lets you replace multiple elements in an array with one, two, or however many elements you like. Just use the syntax: . splice(startingIndex, numDeletions, replacement1, replacement2, ... )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With