如何在 PHP 中替换文本字符串中的多个项目? [重复]

问题描述 投票:0回答:1

我希望能够用

-
替换空格,但也想删除逗号和问号。我怎样才能在一个函数中做到这一点?

到目前为止,我用它替换了空格:

str_replace(" ","-",$title)
php string str-replace
1个回答
270
投票

您可以将数组作为参数传递给

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);
© www.soinside.com 2019 - 2024. All rights reserved.