learnallskill learnallskill - 1 year ago 62
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.)

$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 Source

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


Hi my Hello best World
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download