用Str_Replace替换多个单词

时间:2012-09-30 22:37:12

标签: php string replace

我想用一个特定的单词替换多个同义词。

<?p

$a = array(
'truck',
'vehicle',
'seddan',
'coupe',
'Toyota',
);
$b = array(
'car',
'car',
'car',
'car',
'Lexus',
);
$str = '

Honda is a truck. 
Toyota is a vehicle. 
Nissan is a sedan. 
Scion is a coupe.

';
echo str_replace($a,$b,$str);
?>

结果:本田是一辆汽车。雷克萨斯是一辆车。日产是一辆车。 Scion是一辆汽车。

有人能给我一个干净的方法,用“汽车”代替“车辆,卡车,轿跑车,轿车”而不是我单独更换所有4个。谢谢。

5 个答案:

答案 0 :(得分:8)

$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_replace('Lexus','Toyota',$str));

答案 1 :(得分:3)

您应该使用strtr

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

或者只需将$a$b合并为一个数组

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

输出

Honda is a car. 
Lexus is a car. 
Nissan is a car. 
Scion is a car.

答案 2 :(得分:1)

这样的东西
$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); 

应该工作。

http://codepad.org/1LhtcOSR

编辑:

这样的事情会产生预期的结果:http://pastebin.com/xGzYiCk3

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

输出:

test3 some other stuff some1
test2 some other stuff some2
test3 some other stuff some3
test3 some other stuff some1

答案 3 :(得分:1)

我找到了一个非常简单的解决方案来替换字符串中的多个单词:

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

输出

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

使用此脚本,您可以根据需要替换字符串中的多个单词:

只需将单词(您要替换的单词)放在模式数组中,例如:

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

并将替换数组中的字符(将用于代替替换字符)放置,例如:

      $replacement[0]="new_word"; 

快乐的编码!

答案 4 :(得分:0)

用于将短语替换为其他短语(一次多个)。您可以将数组作为参数传递给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);