2017-09-02 73 views
1

我使用str_replace替换一个字符,如下所示:
str_replace("--","/",$value['judul'])

但我想,以取代2个字符是这样的:
str_replace("--","/",$value['judul'])
str_replace("-+-",":",$value['judul'])
没有做两个str_replace函数。我可以只使用一个str-replace如何Str_replace为多个项目

+0

的可能的复制[如何替换在PHP中的文本字符串多个项目?(https://stackoverflow.com/questions/9393885/how-to-替换多个项目从一个文本字符串在PHP) – localheinz

回答

3

您可以使用strtr()和关联数组做到这一点:

<?php 
$text = "Text about -- and -+- !"; 
$replacements = [ 
    "--" => "/", 
    "-+-" => ":", 
]; 
echo strtr($text, $replacements); // Text about/and : ! 

要添加更多的替代品,只是不断加入更多的元素到$replacements阵列。 Index是要查找的字符串,value是替换字符串。

+0

很高兴我能帮助! – ishegg

+1

@Jazuly'str_replace'也可以和一个数组一起使用,可能希望查看https://stackoverflow.com/questions/8177296/when-to-use-strtr-vs-str-replace获取差异。 – chris85

+0

@ chris85'str_replace()'对此有点烦,因为你需要两个数组。他想减少我猜想的冗长度,所以我就这么说。感谢您的建议! – ishegg