3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Arrays { /** * Replaces in all strings within a multidimensional array, even if objects are included * @param string $search search for this string * @param string $replace_with replace with this string * @param mixed $haystack Array or Object to search in all elements * @return mixed gives the same structure back */ public static function replace_everywhere($search, $replace_with, $haystack) { if (is_array($haystack) or is_object($haystack)) { // Arrays and Objects foreach ($haystack as &$value) { $value = Arrays::replace_everywhere($search, $replace_with, $value); } return $haystack; } elseif (is_string($haystack)) { // replace in a string element return str_replace($search, $replace_with, $haystack); } else { // other datatypes (e.g. integer) stay untouched return $haystack; } } } // You can call this like e.g. $a = array(true, 1, 'foo<bar', 'foo<baz', array("foo<loo"), (object) array('1' => 'foo<boo')); $a = Arrays::replace_everywhere("<", "&lt;", $a); var_export($a);
Output for 8.1.17 - 8.1.28, 8.2.5 - 8.2.19, 8.3.0 - 8.3.7
array ( 0 => true, 1 => 1, 2 => 'foo&lt;bar', 3 => 'foo&lt;baz', 4 => array ( 0 => 'foo&lt;loo', ), 5 => (object) array( '1' => 'foo&lt;boo', ), )

preferences:
45.47 ms | 402 KiB | 31 Q