Question

How can I replace something orderly? for example:

$var = "let's count: ?, ?, ?";

Now I want to replace it by 1, 2, 3 for the result to be "let's count 1, 2, 3". How can I do that? I can't replace by "%s" and use vsprintf() with an array because I wanna respect integers and floats. But I want to do it with an array. For example:

$var = replace( $var, "?", array(1, 2, 3) );

How can I do it? I can't get any idea.

Was it helpful?

Solution

How about:

$var = "let's count: ?, ?, ?";
$numbers = array(1,2,3);

foreach( $numbers as $number ) {
  $var = preg_replace("/\?/", $number, $var, 1);
}

OTHER TIPS

PHP is fun.

$var = "let's count: ?, ?, ?";
$replace = array('1', '2', '3');
$needle = '?';

foreach($replace as $val) {
    $var[strpos($var, $needle)] = $val;
}

Since strpos() will return the first result of the occurance you could do something like this:

$var = "let's count: ?, ?, ?";
$index = 1;
while(strpos($var, '?'))
{
    $var[strpos($var, '?')] = $index;
    $index++;
}
echo $var;

Why you need use substr_count or strpos in answers above? You can use simple for for this task. Look into my example.) This is the most fastest solution for performance.

$var = "let's count: ?, ?, ?";
$replace = array(1,2,3);

for($i=0, $r=0; $i< strlen($var); $i++){

$var[$i] = '?' === $var[$i] ? $replace[$r++] : $var[$i] ;

}

var_dump($var);

Result:

string(20) "let's count: 1, 2, 3" 
$str = "lets count: ?, ?, ?";
$search = "/\?/";
$replace = array(1,2,3);

if( is_array($replace) ) {
  $search = array_fill(0, count($replace), $search);
}

echo preg_replace( $search, $replace, $str, 1);

//output: lets count: 1, 2, 3
$var = "let's count: ?, ?, ?";
$cnt = substr_count($var, '?');

for ($i=1;$i<=$cnt;$i++)
    $var = substr_replace($var, $i, strpos($var, '?'), 1);

echo $var; //let's count: 1, 2, 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top