Replacing all occurrences of a string with values ​​from an array

I parse the string before sending it to the database. I want to pass everything <br>on this line and replace them with the unique numbers that I get from the array, followed by a new line.

For instance:

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"

That sounds easy enough. I just execute a while loop, get all the events <br>using strpos and replace them with the required numbers + \ n using str_replace.

The problem is that I always get an error and I have no idea what I'm doing wrong? Probably a stupid 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,

+5
source share
5 answers

I would use a regex and a custom callback, for example:

$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);

, , $replace. , :

$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);

, :

Line 1 Line 2 Line 3 Line 4 
+6
$str = str_replace('<br>', $replace[$index] . ' ' .'\n', $str);

<br>, .

: substr_replace . :

while($pos = strpos($str, '<br>') !== false )
{
    $str = substr_replace($str, $replace[$replaceIndex] . ' ' .'\n', $pos, 4); // The <br> is four bytes long, so 4 bytes from $pos on.
    $replaceIndex++;
}

( $ , replaceIndex! $replaceIndex )

+1

, .

$str_expl = explode('<br>',$str);
foreach($str_expl as $index=>&$str)
    if(!empty($str))
        $str .= ($index+1);
$str = implode($str_expl);
+1

$ . , php regex, .

<?php
$str     = "Line <br> Line <br> Line <br> Line <br>";
$replace = array("1", "2", "3", "4");
$index = 0;
$count = 1;

while(strpos($str, '<br>') != false )
{
    $str = preg_replace('/<br>/', $replace[$index] . " \n", $str, 1); //str_replace, replaces the first occurance of <br> it finds
    $index++;
}
echo $str
?>
0

. 8 , , KISS.

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

$temp = explode("<br>", $str);
$result = "";
foreach ($temp as $k=>$v) {
    $result .= $v;
    if ($k != count($temp) - 1) {
        $result .= $replace[$k];
    }
}

echo $result;
0

All Articles