php 在同一个字符串上多次使用 str_replace

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16576011/
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-25 11:22:56  来源:igfitidea点击:

Using str_replace multiple times on the same string

phpstr-replace

提问by stepquick

I'm looping through a title from a table so it's essentially something along these lines.

我正在遍历表格中的标题,因此它基本上是沿着这些路线的。

foreach($c as $row){
    echo string_shorten($row['title']);
}

What I'm doing is trying is a switch statement that would switch between what I want it to search for and once it's found replace it with what I choose in the str_replace:

我正在尝试的是一个 switch 语句,它可以在我想要它搜索的内容之间切换,一旦找到,就用我在 str_replace 中选择的内容替换它:

function string_shorten($text){
    switch(strpos($text, $pos) !== false){
         case "Hi":
              return str_replace('Hi','Hello', $text);
         break;
    }
}

Any suggestions or possible alternatives would be appreciated. It feels like I'm really close but not quite.

任何建议或可能的替代方案将不胜感激。感觉就像我真的很接近但又不完全。

回答by kero

As you can read in the manual for str_replace()

正如您可以在手册中阅读的那样str_replace()

mixed str_replace( mixed $search, mixed $replace, mixed $subject[, int &$count] )

混合str_replace(混合$search,混合$replace,混合$subject[,int &$count])

as well as this example

以及这个例子

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);
// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

This means that you could use something like the following

这意味着您可以使用以下内容

$search = array('Hi', 'Heyo', 'etc.');
$replace = array('Hello', 'Hello', '');
$str = str_replace($search, $replace, $str);