Home > Blockchain >  I want to replace two separate words with only one word in PHP
I want to replace two separate words with only one word in PHP

Time:04-25

I want to replace two words in a sentence with one word, like in the following example:

Kippa's luck was very bad yesterday.

I want to change it to:

Kippa's was very misfortune yesterday.

In this example, I know it has no sense, but it's just an example, I want to replace (luck & bad) with the word (misfortune) in php.

Thank you

CodePudding user response:

You can pass arrays as parameters to str_replace

<?php
     $youText  = "Kippa's luck was very bad yesterday.";
     $replace_1 = ["bad", "luck"];
     $replace_2 = ["misfortune", ""];

     $result = str_replace($replace_1, $replace_2, $youText);
     echo $result;
?>

CodePudding user response:

Thank you. but actually there are alot of different words to be changed with, not only one word. I need something like this: **

$URLContent = "he has a bad luck. but he is ok, a good man";

     $remove_multi = array(['bad', 'luck'],
                           ['good', 'man']);
                            
     $replace_multi = array(['misfortune', ''],
                            ['nice', '']);


$URLContent = str_replace($remove_multi, $replace_multi, $URLContent);
  • Related