字符串替换不同的结果

String replace different result

$string = "[abc] my [efg] best [hij]";

先[]改成嗨
第二个[]改为Hello.
第三【】改成World.

整个字符串都是动态的。 (它总是显示不同的结果。) 示例:

$string = "[iii] my my [ooo] yes to all [eee]";
$string = "[abc] lovely [efg] [hij]";
$string = "[abc] my [efg] best of the the the the [hij]. That Right.";

我可以尝试这段代码,但它会将所有代码替换为相同的值。

$string = preg_replace('/\[(.*?)\]/',"Hi",$string );

替换一次就会变成Hi Hello World。可以 str_replace 字符串吗?

您可以使用函数 explode:

<?php
    $string = "[abc] my [efg] best [hij]";         

    $ar = explode(" ", $string);             

    $ar[0] = 'Hi';                       
    $ar[2] = 'Hello';                       
    $ar[4] = 'World';

    echo implode(' ', $ar); //Hi my Hello best World

你想改变整个文本,所以这里不需要条件..

$string = "[abc] [efg] [hij]";
$change = "Hi Hello World";
echo str_replace($string,$change,$string);

这里有一个方法:

$string = "[abc] my [efg] best [hij]"; 
$repl = array('Hi', 'Hello', 'World');
foreach($repl as $word) {
    $string = preg_replace('/\[[^\]]+\]/', $word, $string, 1);
}
echo $string,"\n";

输出:

Hi my Hello best World