4

I want to write a function that allows me to replace repetitions of a token in a string with sucessive values from an array, so that WHERE name = ? and age ?, array('joe', 32) becomes Where name = joe and age = 32. (I know variable binding should not be done "manually"; I'm trying to troubleshoot the arguments passed to an eloquent DB::select statement).

I wrote this:

function str_replace_array($search, array $replace, $subject ) {
    foreach ( $replace as $replacement ) {
        $subject = str_replace($search, $replacement,$subject,1);
    }
    return $subject;
}

But php 5.6.20 gives me this error:

$ php -l str_replace_array.php
PHP Fatal error:  Only variables can be passed by reference in str_replace_array.php on line 5
Errors parsing str_replace_array.php

I know it's the function str_replace(), because replacing it with a dummy function allows it to pass a syntax check. Although, none have the same variable as both the assignee and and argument-- but is there anything to indicate this wouldn't work in this function?

The manual entry doesn't indicate that any arguments are passed by reference; it indicates a return value and all the examples show assignment.

What is the deal here?

user151841
  • 17,377
  • 29
  • 109
  • 171

2 Answers2

4

Its due to the last parameter of str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) that you are setting directly to 1, you need to set that to some variable say $count, as its value will be set to the number of replacements performed. So change to:

..
$subject = str_replace($search, $replacement,$subject, $count);
..
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

Last parameter of str_replace takes varible to save count, not to make replacement n-times;

use preg_replace

function str_replace_array($search, $replace, $subject ) {
    foreach ( $replace as $replacement ) {
        $subject = preg_replace("/\?/", $replacement,$subject, 1);
    }
    return $subject;
}
echo (str_replace_array("?",array(1,2,3),"awdwad ? asdaw ? awdwa? awd"));

result: "awdwad 1 asdaw 2 awdwa3 awd"