-1

Array ( [0] => Array ( [trigger] => E [alttext] => C ) [1] => Array ( [trigger] => F [alttext] =>D ) )

foreach ($trigger as $tdata) {
                $tr = $tdata['trigger'];
                $ttext = $tdata['alttext'];
                $text= str_replace($tr, $ttext, 'A B E F');
           //If im echo this result then result is 
           Result = A B C F A B E D

            }

And:

   foreach ($trigger as $tdata) {
                $tr = $tdata['trigger'];
                $ttext = $tdata['alttext'];
                $text= str_replace($tr, $ttext, 'A B E F');
                      }
            //If im echo this result then result is 
          Result = A B E D

But I want to show A B C D

Thanks In Advance!

Shuvo
  • 17
  • 5

2 Answers2

2

I think the problem is that you are always going back to the original string to do the replacement - you need to do accumulative changes. So here it sets $text with the original string and each time does the replacements in this string...

   $text = 'A B E F';
   foreach ($trigger as $tdata) {
       $tr = $tdata->trigger;
       $ttext = $tdata->alttext;
       $text= str_replace($tr, $ttext, $text);
    }

    echo $text;

The only thing you have to be careful about with this method is that if the text you replace with earlier is something you later search and replace with. So E -> F and F -> D would be A B D D.

Update:

With your test data...

$trigger = Array ( Array ( "trigger" => "E", "alttext" => "C" ) , 
    Array ( "trigger" => "F", "alttext" =>"D" ) );
$text = 'A B E F';
foreach ($trigger as $tdata) {
    $tr = $tdata['trigger'];
    $ttext = $tdata['alttext'];
    $text= str_replace($tr, $ttext, $text);
}

echo $text;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

Consider this (assuming these are similar to your database rows):

<?php
$rows = [
    ['E', 'C'],
    ['F', 'D']
];

foreach($rows as $row) {
    $find    = $row[0];
    $replace = $row[1];
    echo str_replace($find, $replace, 'A B E F');
}

Output:

A B C FA B E D

We could do this in one pass via the following two methods:

You can pass str_replace two arrays of corresponding find and replaces:

echo str_replace(array_column($rows, 0), array_column($rows, 1), 'A B E F');

Output:

A B C D

Or use strtr with an array (from => to) (['E'=>'C', 'F'=>'D']):

  echo strtr('A B E F', array_column($rows, 1, 0));

Output:

A B C D

You'll have to build your arrays of find and replacements, and use one of those methods that suits. Note there is slight difference in the way str_replace and strtr substitutes.

Progrock
  • 7,373
  • 1
  • 19
  • 25
  • `Array ( [0] => Array ( [trigger] => E [alttext] => C ) [1] => Array ( [trigger] => F [alttext] =>D ) )` my data Base structure – Shuvo Oct 26 '19 at 13:26