3v4l.org

run code in 300+ PHP versions simultaneously
<?php function replace2($matches, $replacements, $frame) { if (!isset($matches[0]) || !is_array($matches[0]) || empty($matches[0])) { return []; } $result = []; foreach ($matches[0] as $value) { if (isset($replacements[$value])) { foreach ($replacements[$value] as $v) { $tmp = str_replace($value, $v, $frame); $result[$tmp] = $tmp; array_shift($matches); replace2($matches, $replacements, $frame); } } } return $result; } function doStuff($frame) { $replacements = [ '{childName}' => [], '{favoriteFood}' => ['pizza', 'soup', 'burger'], '{favoriteToy}' => ['doll', 'teddy bear', 'truck', 'computer'] ]; preg_match_all('/'.implode('|', array_keys($replacements)).'/', $frame, $matches); if (count($matches[0]) < 1) { return [$frame => null]; } return replace2($matches, $replacements, $frame); } $frames = [ '{childName} loves to eat {favoriteFood} and play with his or her {favoriteToy}', '{childName} loves to eat {favoriteFood}', '{childName} loves to play' ]; foreach ($frames as $frame) { var_dump(doStuff($frame)); echo "\n"; }
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.7
array(7) { ["{childName} loves to eat pizza and play with his or her {favoriteToy}"]=> string(69) "{childName} loves to eat pizza and play with his or her {favoriteToy}" ["{childName} loves to eat soup and play with his or her {favoriteToy}"]=> string(68) "{childName} loves to eat soup and play with his or her {favoriteToy}" ["{childName} loves to eat burger and play with his or her {favoriteToy}"]=> string(70) "{childName} loves to eat burger and play with his or her {favoriteToy}" ["{childName} loves to eat {favoriteFood} and play with his or her doll"]=> string(69) "{childName} loves to eat {favoriteFood} and play with his or her doll" ["{childName} loves to eat {favoriteFood} and play with his or her teddy bear"]=> string(75) "{childName} loves to eat {favoriteFood} and play with his or her teddy bear" ["{childName} loves to eat {favoriteFood} and play with his or her truck"]=> string(70) "{childName} loves to eat {favoriteFood} and play with his or her truck" ["{childName} loves to eat {favoriteFood} and play with his or her computer"]=> string(73) "{childName} loves to eat {favoriteFood} and play with his or her computer" } array(3) { ["{childName} loves to eat pizza"]=> string(30) "{childName} loves to eat pizza" ["{childName} loves to eat soup"]=> string(29) "{childName} loves to eat soup" ["{childName} loves to eat burger"]=> string(31) "{childName} loves to eat burger" } array(0) { }

preferences:
216.16 ms | 407 KiB | 331 Q