learnallskill learnallskill - 5 months ago 16
PHP Question

String replace different result

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


first [] change to Hi.

second [] change to Hello.

third [] change to World.



The entire string are dynamic. (It is always show different result.)
Example:

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


I can tried this code, but it replace all to same value.

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


Once replace will become Hi Hello World. Can str_replace string to that?

Answer

Here is a way to go:

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

Output:

Hi my Hello best World