Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 485
stepquick Avatar asked May 15 '13 22:05

stepquick


People also ask

How can I replace multiple words in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

How do I replace a pattern in a string in R?

R – str_replace() to Replace Matched Patterns in a String. R str_replace() and str_replace_all() are used to replace values of a string column based on matched patterns ( pattern matching with regex – regular expression), also used to replace with a specific string or character value.

How to replace all character in a string in PHP?

The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by replacement string or array of replacement strings in the given string or array respectively.


1 Answers

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);
like image 130
kero Avatar answered Oct 04 '22 15:10

kero