如何从 PHP 中的文本字符串中替换多个项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9393885/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:43:04 来源:igfitidea点击:
How to replace multiple items from a text string in PHP?
提问by James Brandon
I want to be able to replace spaces with -
but also want to remove commas and question marks. How can I do this in one function?
我希望能够替换空格,-
但也希望删除逗号和问号。我怎样才能在一个函数中做到这一点?
So far, I have it replacing spaces:
到目前为止,我已经用它替换了空格:
str_replace(" ","-",$title)
回答by Napolux
You can pass arrays as parameters to str_replace()
. Check the manual.
您可以将数组作为参数传递给str_replace()
. 检查手册。
// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = ["fruits", "vegetables", "fiber"];
$yummy = ["pizza", "beer", "ice cream"];
$newPhrase = str_replace($healthy, $yummy, $phrase);