Replace multiple words with Str_Replace

后端 未结 5 2204
醉梦人生
醉梦人生 2021-01-05 18:50

I want to replace multiple synonyms with one specific word.



        
相关标签:
5条回答
  • 2021-01-05 19:03

    Something like

    $a = array( 'truck', 'vehicle', 'seddan', 'coupe' ); 
    
    $str = 'Honda is a truck. Toyota is a vehicle. Nissan is a sedan. Scion is a coupe.'; 
    
    echo str_replace($a,'car',$str); 
    

    Should work.

    http://codepad.org/1LhtcOSR

    Edit:

    Something like this should yield expected results: http://pastebin.com/xGzYiCk3

    $text = '{test|test2|test3} some other stuff {some1|some2|some3}';
    

    Output:

    test3 some other stuff some1
    test2 some other stuff some2
    test3 some other stuff some3
    test3 some other stuff some1
    
    0 讨论(0)
  • 2021-01-05 19:15

    For replacing phrases with other phrases (multiple at a time). You can pass arrays as parameters to str_replace()

    // Provides: You should eat pizza, beer, and ice cream every day
    $phrase  = "You should eat fruits, vegetables, and fiber every day.";
    $healthy = ["fruits", "vegetables", "fiber"];
    $yummy   = ["pizza", "beer", "ice cream"];
    
    $newPhrase = str_replace($healthy, $yummy, $phrase);
    
    0 讨论(0)
  • 2021-01-05 19:20

    You should use strtr

    echo strtr($str,array_combine($a,$b)); 
    

    Or Just combine $a and $b into one array

    $ab = array('truck' => 'car','vehicle' => 'car','sedan' => 'var','coupe' => 'var','Toyota' => 'Lexus');
    echo strtr($str, $ab);
    

    Output

    Honda is a car. 
    Lexus is a car. 
    Nissan is a car. 
    Scion is a car.
    
    0 讨论(0)
  • 2021-01-05 19:25

    I found a very easy solution to replace multiple words in a string :

    <?php
     $str="    Honda is a truck. 
    Toyota is a vehicle. 
    Nissan is a sedan. 
    Scion is a coupe.";
    
    
    $pattern=array();
    $pattern[0]="truck";
    $pattern[1]="vehicle";
    $pattern[2]="sedan";
    $pattern[3]="coupe";
    
    
    
    $replacement=array();
    $replacement[0]="car";
    $replacement[1]="car";
    $replacement[2]="car";
    $replacement[3]="car";
    
    
    
    echo str_replace($pattern,$replacement,$str);?> 
    

    output :

      Honda is a car. 
    Toyota is a car. 
    Nissan is a car. 
    Scion is a car
    

    With this script you can replace as many words in a string as you want :

    just place the word (that you want to replace) in the pattern array , eg :

         $pattern[0]="/replaceme/"; 
    

    and place the characters (that will be used in place of the replaced characters) in the replacement array, eg :

          $replacement[0]="new_word"; 
    

    Happy coding!

    0 讨论(0)
  • 2021-01-05 19:29
    $a = array( 'truck', 'vehicle', 'sedan', 'coupe' );
    $str = 'Honda is a truck. Toyota is a vehicle. Nissan is a sedan. Scion is a coupe.';
    echo str_replace($a,'car',str_replace('Toyota','Lexus',$str));
    
    0 讨论(0)
提交回复
热议问题