php str_replace() 用于多值替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24554723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
str_replace() for multiple value replacement
提问by user3754380
Is there any possibility to use str_replace
for multiple value replacement in a single line. For example i want to replace ' '
with '-'
and '&'
with ''
?
是否有可能str_replace
在一行中用于多个值替换。例如我想替换' '
用'-'
和'&'
用''
?
回答by Boaz - Reinstate Monica
str_replace()
accepts arrays as arguments.
str_replace()
接受数组作为参数。
For example:
例如:
$subject = 'milk is white and contains sugar';
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);
In fact, the third argument can also be an array, so you can make multiple replacements in multiple values with a single str_replace()
call.
事实上,第三个参数也可以是一个数组,因此您可以通过一次str_replace()
调用在多个值中进行多次替换。
For example:
例如:
$subject = array('milk contains sugar', 'sugar is white', 'sweet as sugar');
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);
As others have noted, this is clearly stated in the manual:
正如其他人所指出的,手册中明确说明了这一点:
searchThe value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
replaceThe replacement value that replaces found search values. An array may be used to designate multiple replacements.
subjectThe string or array being searched and replaced on, otherwise known as the haystack.
search正在搜索的值,也称为针。阵列可用于指定多个针。
replace替换找到的搜索值的替换值。数组可用于指定多个替换。
subject被搜索和替换的字符串或数组,也称为 haystack。
回答by sid busa
$name = abcd;
I want to replace 'a' with '$' and 'b' with '!', so I need to write like this:
我想用 '$' 替换 'a',用 '!' 替换 'b',所以我需要这样写:
$str = ['a','b'];
$rplc =['$','!'];
echo str_replace("$str","$rplc",$name);
output : $!cd
输出 : $!cd
回答by swlim
Take note of the order of the arrays as it corresponds to the order.
Like for below, A is replaced with B, B with C and so on.. so there you go.
注意数组的顺序,因为它对应于顺序。就像下面一样,A 替换为 B,B 替换为 C 等等......所以你去。
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
source: PHP str_replace
回答by Team Work
Yes with the help of str_replace function we can do multiple value replacement in a single line without array.Here is my code
是的,在 str_replace 函数的帮助下,我们可以在没有数组的情况下在一行中进行多个值替换。这是我的代码
echo str_replace(" ","-",str_replace("&","","I like Tea&Coffee"));