Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all occurrences of a string with values from an array

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,

like image 351
r3x Avatar asked Apr 22 '13 16:04

r3x


People also ask

How do you replace all occurrences in a string?

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.

Does string replace replace all occurrences?

Finally, the new string method string. replaceAll(search, replaceWith) replaces all string occurrences.

How do you replace all elements in an array?

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.

How do you replace multiple elements in an array?

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, ... )


1 Answers

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 
like image 143
nickb Avatar answered Oct 21 '22 00:10

nickb