Sydowh Sydowh - 13 days ago 4
PHP Question

str_replace $v* with a php variable

I got some text in html like this

<p>Test test test $v1 $v2 $v3 $v11</p>


With PHP I need to replace $v1 $v2 $v3 ... $v9, I don't need to replace $v10 ... $v*****

My problem is when I have $v11 in my text it's replacing $v1 + 1 at the end :

$v1 = "here";
...
What I got actually : Test test test $v11 => Test test test here1
I need :Test test test $v11 => Test test test


$vars is an array in PHP :

$v1 = "here";
$v2 = "";
$v3 = "";
$v4 = "";
$v5 = "";
$v6 = "";
$v7 = "";
$v8 = "";
$v9 = "";
$vars = array($v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9);


My function

function replaceVar($vars, $string)
{
$stringReplace = '$v';
$i = 1;
while ($i <= 9) {
if(!empty($vars[$i]) && strlen($stringReplace . $i) == 3)
{
$string = str_replace('$v' . $i, $vars[$i], $string);
}
else
{
$string = str_replace('$v' . $i, "", $string);
}
$i++;
}
return $string;
}


Excepted output :
$vars is an array in PHP :

$v1 = "here";
$v2 = "";
$v3 = "";
$v4 = "";
$v5 = "";
$v6 = "";
$v7 = "";
$v8 = "";
$v9 = "";
$vars = array($v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9);

echo replaceVar($vars, "Test test test $v1 $v2 $v11");


Test test test here

Answer

You can use preg_replace_callback for this. Try the following

<?php
 $str = '<p>Test test test $v1 $v2 $v3 $v11</p>';

$v1 = "here";
$v2 = "";
$v3 = "";
$v4 = "";
$v5 = "";
$v6 = "";
$v7 = "";
$v8 = "";
$v9 = "";
$vars = array($v1,$v2,$v3,$v4,$v5,$v6,$v7,$v8,$v9);

echo preg_replace_callback('/\$v(\d)\s/', 
       function($match) use ($vars) { return ($vars[$match[1]-1]) . ' '; },
       $str);

Note : return ($vars[$match[1]-1]) the -1 is there because your 0th element in the $vars array is actually for $v1

Demo Here

Note: I am assuming there is a space after &v1 otherwise you may have to change the match and replacement.

Explanation:

'/\$v(\d)\s/' match for $v and a digit and a space

return ($vars[$match[1]-1]) . ' '

for each match return the element from $vars array with index matched value-1. so if (\d) matches 1 it will return $vars[1-1]