且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

str_replace()用于多值替换

更新时间:2021-12-15 22:47:53

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:

搜索 要搜索的值,否则称为针.阵列可用于指定多个针头.

search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

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

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.