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>'.$haystack.'</pre>'; echo '<hr>'; echo '<h1>After replace:</h1>'; echo '<pre>'.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.38, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.25, 7.3.0 - 7.3.12, 7.4.0
<h1>Before replace:</h1><pre>hello /r/n im showing some code /r/n [CODE=HTML] <html> /r/n /r/n </html> [/CODE]/r/n thanks</pre><hr><h1>After replace:</h1><pre>hello <br> im showing some code <br> [CODE=HTML] <html> /r/n /r/n </html> [/CODE]<br> 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/VIktR 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/VIktR 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/VIktR on line 3
Process exited with code 255.

preferences:
219.02 ms | 401 KiB | 317 Q