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>';

preferences:
28.33 ms | 402 KiB | 5 Q