3v4l.org

run code in 300+ PHP versions simultaneously
<?php class str_replace_except_code { protected static $uniq; protected static $needle; protected static function replaceCB($matches){ return preg_replace("/".self::$uniq."/", self::$needle, $matches[0]); } /** * Replaces all instances of $needle found in $haystack with $replace except where $needle is between [CODE] tags. * @param string $haystack The string to search for instances of $needle * @param string $needle The string to find within $haystack * @param string $replace The replacement value * @return string $haystack with all instances of $needle replaced with $replace where not between [CODE] tags */ public static function go($haystack, $needle, $replace){ //generate a uniq string that shouldn't exist in the haystack self::$uniq = uniqid('UNIQ_', true); self::$needle = $needle; //replace all occurrences of the needle with the unique string $haystack = str_replace($needle, self::$uniq, $haystack); //replace all instances of the unique string between [code] tags with the original string $needle $haystack = preg_replace_callback("/\[CODE[^\]]*\].*?\[\/CODE\]/is", array('str_replace_except_code', 'replaceCB'), $haystack); //replace all remaining unique strings, which should be only those outside [code] tags with the replacement string $haystack = str_replace(self::$uniq, $replace, $haystack); //return the original string with the correct replacements return $haystack; } } $haystack =<<<POST hello /r/n im showing some code /r/n [CODE=HTML] <html> /r/n /r/n </html> [/CODE]/r/n thanks POST; $needle = "/r/n"; $replace= "<br>"; echo '<h1>Before replace:</h1>'; echo '<pre>'.htmlentities($haystack).'</pre>'; echo '<hr>'; echo '<h1>After replace:</h1>'; echo '<pre>'.htmlentities(str_replace_except_code::go($haystack, $needle, $replace)).'</pre>';
Output for 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 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.26, 7.3.0 - 7.3.13, 7.4.0 - 7.4.1
<h1>Before replace:</h1><pre>hello /r/n im showing some code /r/n [CODE=HTML] &lt;html&gt; /r/n /r/n &lt;/html&gt; [/CODE]/r/n thanks</pre><hr><h1>After replace:</h1><pre>hello &lt;br&gt; im showing some code &lt;br&gt; [CODE=HTML] &lt;html&gt; /r/n /r/n &lt;/html&gt; [/CODE]&lt;br&gt; thanks</pre>
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/a7c3F on line 3
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/a7c3F on line 3
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in /in/a7c3F on line 3
Process exited with code 255.

preferences:
228.96 ms | 401 KiB | 325 Q