Using str_replace multiple times on the same string

安稳与你 提交于 2020-01-10 02:38:25

问题


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:

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.


回答1:


As you can read in the manual for str_replace()

mixed str_replace ( mixed $search , mixed $replace , mixed $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);

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);


来源:https://stackoverflow.com/questions/16576011/using-str-replace-multiple-times-on-the-same-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!