12

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.

6
  • 1
    str_replace() will accept arrays as the from and to arguments - php.net/manual/en/function.str-replace.php Commented May 15, 2013 at 22:25
  • Not all the strings will be replaced the same way. in one case one word is being replaced with an abbreviation, and another is being completely removed. Commented May 15, 2013 at 22:28
  • 1
    You can also make the replacements an array Commented May 15, 2013 at 22:28
  • Your switch has case TRUE/FALSE, and "Hi" is same as TRUE. php.net/language.types.type-juggling Commented May 15, 2013 at 22:29
  • @stepquick - so build your replace array accordingly Commented May 15, 2013 at 22:31

1 Answer 1

45

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.