Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

php - Using str_replace multiple times on the same string

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...