本文介绍了str_replace()用于多值替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在单行中使用str_replace进行多值替换.例如我想用'-'替换' '并用''替换'&'?

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() 接受数组作为参数.

str_replace() accepts arrays as arguments.

例如:

$subject = 'milk is white and contains sugar';
str_replace(array('sugar', 'milk'), array('sweet', 'white'), $subject);

实际上,第三个参数也可以是数组,因此您可以通过一次str_replace()调用在多个值中进行多次替换.

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.

例如:

$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:

替换 替换找到的搜索值的替换值.数组可用于指定多个替换项.

replace The replacement value that replaces found search values. An array may be used to designate multiple replacements.

主题 正在搜索并替换的字符串或数组,否则称为干草堆.

subject The string or array being searched and replaced on, otherwise known as the haystack.

这篇关于str_replace()用于多值替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:16