php 在 PHP5 中用多个/不同的值搜索和替换多个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/535143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:01:18  来源:igfitidea点击:

Search and replace multiple values with multiple/different values in PHP5?

phparraysstringreplace

提问by atomicharri

Is there an inbuilt PHP function to replace multiple values inside a string with an array that dictates exactly what is replaced with what?

是否有一个内置的 PHP 函数可以用一个数组替换字符串中的多个值,该数组确切地指示用什么替换什么?

For example:

例如:

$searchreplace_array = Array('blah' => 'bleh', 'blarh' => 'blerh');
$string = 'blah blarh bleh bleh blarh';

And the resulting would be: 'bleh blerh bleh bleh blerh'.

结果将是:'bleh bleh bleh bleh bleh'。

回答by lpfavreau

You are looking for str_replace().

您正在寻找str_replace().

$string = 'blah blarh bleh bleh blarh';
$result = str_replace(
  array('blah', 'blarh'), 
  array('bleh', 'blerh'), 
  $string
);

// Additional tip:

// 额外提示:

And if you are stuck with an associative array like in your example, you can split it up like that:

如果您像示例中那样使用关联数组,则可以将其拆分如下:

$searchReplaceArray = array(
  'blah' => 'bleh', 
  'blarh' => 'blerh'
);
$result = str_replace(
  array_keys($searchReplaceArray), 
  array_values($searchReplaceArray), 
  $string
); 

回答by nithi

$string = 'blah blarh bleh bleh blarh';
$trans = array("blah" => "blerh", "bleh" => "blerh");
$result = strtr($string,$trans);

You can check the manualfor detailed explanation.

您可以查看手册以获取详细说明。

回答by T.Adak

IN CASE some one is looking for replacing same strings with different values ( per occurence ).. Example, to replace all ##by numbers++ OR values from an array-

万一有人想用不同的值(每次出现)替换相同的字符串。例如,用数字++或数组中的值替换所有## -

$split_at = '##';
$string = "AA ##  BB ##  CC ##  DD";
$new_string = '';
// echo $string;
$replace_num = 1;
$replace_arr = ['first' , 'second' , 'third'];
$split_at_cnt = substr_count($string, $split_at);
for ($split=0; $split <= $split_at_cnt; $split++)
{
    $new_string .= str_replace('##', ($replace_num++)." : ".$replace_arr[$split], substr( $string, 0, strpos($string, $split_at)+strlen($split_at)));
    $string = substr($string, strpos($string, $split_at)+strlen($split_at));
}

echo $new_string;

回答by chaos

str_replace()does that.

str_replace()这样做。

You can check the manualfor more detailed explanation.

您可以查看手册以获取更详细的说明。

回答by chaos

For what you've got there, just pass that array into str_replaceas both the search and replace (using array_keyson the search parameter if you want to keep the array as-is).

对于您所拥有的内容,只需将该数组str_replace作为搜索和替换传递给(array_keys如果您想保持数组原样,则在搜索参数上使用)。