user151841
user151841

Reputation: 18046

What's special about `str_replace`?

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?

Upvotes: 4

Views: 280

Answers (2)

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"

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100195

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

Upvotes: 4

Related Questions