Php 字符串替换不同的结果

Php 字符串替换不同的结果,php,preg-replace,Php,Preg Replace,第一[]更改为Hi。 第二个[]更改为Hello。 第三[]改变世界。 整个字符串是动态的。(总是显示不同的结果。) 例如: $string = "[abc] my [efg] best [hij]"; 我可以尝试此代码,但它将所有代码替换为相同的值 $string = "[iii] my my [ooo] yes to all [eee]"; $string = "[abc] lovely [efg] [hij]"; $string = "[abc] my [efg] best of the

第一[]更改为Hi。
第二个[]更改为Hello。
第三[]改变世界。

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

$string = "[abc] my [efg] best [hij]";
我可以尝试此代码,但它将所有代码替换为相同的值

$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.";

一旦替换,将成为Hi Hello World。str_可以替换字符串吗?

您可以使用函数
explode

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

您可以使用函数
分解

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

您希望更改整个文本,因此此处不需要条件

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

您希望更改整个文本,因此此处不需要条件

<?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";
这里有一条路要走:

$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 change
$string=“测试”
$string=“测试”
或在
第二次测试时更改为Hello。
您的问题存在冲突。Hi change
$string=“test tests”
$string=“测试”
或在
第二次测试时更改为Hello。
您的问题存在冲突。非常抱歉,让您感到困惑。我意识到我问错了问题。我编辑了我的问题。再一次sorry@learnallskill没问题。我编辑答案,你们可以用。很抱歉把你们搞糊涂了。我意识到我问错了问题。我编辑了我的问题。再一次sorry@learnallskill没问题。我编辑答案,你们可以使用它。