3v4l.org

run code in 500+ PHP versions simultaneously
<?php $format='<number_from_format>{{number}}</number_from_format>{{prefix}}'; // Here {{prefix}} is first and {{number}} is last: $replacements = [ '{{prefix}}' => "<number_from_prefix>{{number}}</number_from_prefix>", '{{number}}' => 123, ]; $old=str_replace(array_keys($replacements), array_values($replacements), $format); $new=strtr($format,$replacements); var_dump($old,$new); // Now flip it, {{prefix}} last and {{number}} first: $format='<number_from_format>{{number}}</number_from_format>{{prefix}}'; $replacements = [ '{{number}}' => 123, '{{prefix}}' => "<number_from_prefix>{{number}}</number_from_prefix>", ]; $old=str_replace(array_keys($replacements), array_values($replacements), $format); $new=strtr($format,$replacements); var_dump($new,$old); // now lets do that with strtr_recursive: function strtr_recursive(string $str, array $table, int $maxDepth = 100): string { $depth = 0; while ($depth < $maxDepth) { $old = $str; $str = strtr($str, $table); if ($old === $str) { return $str; } ++$depth; } throw new \RuntimeException("translation exceeded max recursion depth ($maxDepth)"); } // with strtr_recursive, it does not matter if {{number}} or {{prefix}} comes first. $format='<number_from_format>{{number}}</number_from_format>{{prefix}}'; $replacements = [ '{{number}}' => 123, '{{prefix}}' => "<number_from_prefix>{{number}}</number_from_prefix>", ]; $old=str_replace(array_keys($replacements), array_values($replacements), $format); $new=strtr_recursive($format,$replacements); var_dump($old,$new);

preferences:
22.05 ms | 477 KiB | 4 Q