简体   繁体   English

`str_replace`有什么特别之处?

[英]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 ? 我想编写一个函数,允许我用数组中的过多值替换字符串中令牌的重复,以便WHERE name = ? and age ? WHERE name = ? and age ? , array('joe', 32) becomes Where name = joe and age = 32 . array('joe', 32)变为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). (我知道变量绑定不应该“手动”完成;我正在尝试解决传递给eloquent DB::select语句的参数)。

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 5.6.20给了我这个错误:

$ 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. 我知道它是函数str_replace() ,因为用虚函数替换它允许它传递语法检查。 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? 这是什么交易?

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. 由于str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )的最后一个参数str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )你直接设置为1 ,你需要将它设置为某个变量,比如$count ,因为它value将设置为执行的替换次数。 So change to: 所以改为:

..
$subject = str_replace($search, $replacement,$subject, $count);
..

Last parameter of str_replace takes varible to save count, not to make replacement n-times; str_replace的最后一个参数需要varible来保存计数,而不是替换n次;

use preg_replace 使用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" 结果:“awdwad 1 asdaw 2 awdwa3 awd”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM