如何Str_replace为多个项目
问题描述:
我使用str_replace替换一个字符,如下所示:str_replace("--","/",$value['judul'])
。
但我想,以取代2个字符是这样的:str_replace("--","/",$value['judul'])
和str_replace("-+-",":",$value['judul'])
没有做两个str_replace函数。我可以只使用一个str-replace
?如何Str_replace为多个项目
答
您可以使用strtr()
和关联数组做到这一点:
<?php
$text = "Text about -- and -+- !";
$replacements = [
"--" => "/",
"-+-" => ":",
];
echo strtr($text, $replacements); // Text about/and : !
要添加更多的替代品,只是不断加入更多的元素到$replacements
阵列。 Index是要查找的字符串,value是替换字符串。
的可能的复制[如何替换在PHP中的文本字符串多个项目?(https://stackoverflow.com/questions/9393885/how-to-替换多个项目从一个文本字符串在PHP) – localheinz