将str_replace应用于不匹配的字符串部分

时间:2015-08-18 18:22:22

标签: php regex

我正在从回复到"线程"解析表单发布数据在我的网站上,我正在使用Prism将sytaxing添加到代码中

现在这是我的问题:

我使用php将帖子内容回显到div中,但是由于div工作\r\n的行为不是新行,而是<br>

但棱镜脚本 DOES 使用\r\n来表示换行符,因为它可以包含的内容(带有
的html代码等)

所以基本上我需要解析所有不在

之间的代码
[CODE] and [/CODE] semi bb code

并将所有\ r \ n更改为 <br>那里

所以这样的帖子回复:

hello \r\n
im showing some code /r/n
[CODE=HTML]
<html> \r\n
\r\n
</html>
[/CODE]\r\n
thanks

成:

hello <br>
im showing some code <br>
[CODE=HTML]
<html> \r\n
\r\n
</html>
[/CODE]<br>
thanks

目前我正在使用php将所有\r\n替换为<br>,但这明显打破了棱镜

$cleancontent = str_replace("\r\n", "<br>", $cleancontent);

我如何使用正则表达式(或任何其他解决方案)来查找不在之间的所有内容 &#34; [CODE&#34;和&#34; [/ CODE]&#34;并将\r\n替换为<br>

1 个答案:

答案 0 :(得分:0)

这是我建议的一个例子。

演示:http://codepad.viper-7.com/bSODv7

<?php
class preg_replace_except_code {
    protected static $uniq;
    protected static $pattern;

    protected static function replaceCB($matches){
        return preg_replace("/".self::$uniq."/", '', $matches[0]);
    }

    /**
     * Replaces all instances of $pattern found in $haystack with $replace except where $pattern is between [CODE] tags.
     * @param  string $haystack The string to search for instances of $pattern
     * @param  string $pattern   The string to find within $haystack
     * @param  string $replace  The replacement value
     * @return string           $haystack with all instances of $pattern replaced with $replace where not between [CODE] tags
     */
    public static function go($haystack, $pattern, $replace){
        //generate a uniq string that shouldn't exist in the haystack
        self::$uniq = uniqid('UNIQ_', true);
        self::$pattern = $pattern;

        //replace all occurrences of the needle with the unique string
        $haystack = preg_replace($pattern, self::$uniq.'$0', $haystack);

        //replace all instances of the unique string between [code] tags with the original string $pattern
        $haystack = preg_replace_callback("/\[CODE[^\]]*\].*?\[\/CODE\]/is", array('preg_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
im showing some code
[CODE=HTML]
<html>

</html>
[/CODE]
thanks
POST;

$pattern = "/\r\n|\r|\n/";
$replace= "<br>";

echo '<h1>Before replace:</h1>';
echo '<pre>'.htmlentities($haystack).'</pre>';
echo '<hr>';
echo '<h1>After replace:</h1>';
echo '<pre>'.htmlentities(preg_replace_except_code::go($haystack, $pattern, $replace)).'</pre>';