PHP正则表达式-单引号不起作用-TWIG预转义


PHP Regular Expression - Single Quote not working - TWIG pre-escaping

我在正则表达式中遇到了单引号问题。我想做的是将字符串中的smileys替换为html图像标记。所有的微笑都在起作用,除了悲伤的微笑:"-(因为它只有一句话。Magic Quotes已关闭(带有if(g!et_Magic_Quotes_gpc())dd('mq-off');的测试集)。

那么,让我给你看一些代码。

    protected $emoticons = array(
        // ...
        'cry' => array(
            'image' => '<img class="smiley" src="/image/emoticon/cry.gif" />',
            'emoticons' => array(":'(", ";'(", ":'-(", ";'-(")
        ),
    );

我替换所有表情符号的方法如下:

    public function replaceEmoticons($input) {
        $output = $input;
        foreach ($this->emoticons as $emo_group_name => $emo_group) {
            $regex_emo_part = array();
            foreach ($emo_group['emoticons'] as $emoticon) {
                $regex_emo_part[] = preg_quote($emoticon, '#');
            }
            $regex_emo_part = implode('|', $regex_emo_part);
            $regex = '#(?!<'w)(' . $regex_emo_part .')(?!'w)#';
            $output = preg_replace($regex, $emo_group['image'], $output);
        }
        return $output;
    }

但正如我所说:'杀死它。没有替代品。:-)://等等都在起作用。为什么?仅供参考$regex:#(?!<'w)(':'''(|;'''(|':'''-'(|;'''-'()(?!'w)# 的内容

这里怎么了,你能帮我吗?

更新:

谢谢@cheely和cychoi。更换方法还可以,你说得对。我发现了问题。我的字符串在转发到replaceEmoticons方法之前进行了转义。我使用TWIG模板引擎,在我自己制作的replace_emoticon过滤器之前使用|nl2br过滤器。让我给你看看。这是最终模板中的输出。这是一个显示博客评论的模板:

{{ comment.content|nl2br|replace_emoticons|raw }}

问题:nl2br自动预转义输入字符串,因此'被转义后的字符串替换&039;

我需要这个nl2br将换行符显示为<br/>-我也需要转义,以禁止用户输入中的html标记。我需要replace_emoticons来替换我的表情符号(自制TWIG扩展)。我在过滤链的末尾也需要raw,否则所有的HTML smiley img标签都会被转义,我会在评论的文本中看到raw HTML。

我在这里能做什么?这里唯一的问题似乎是nl2br也逃脱了。这不是一个坏主意,但在我的情况下,它会摧毁所有包含"悲伤的微笑"。

仍在寻找解决方案,我希望你能帮助我。

最佳,titan

我为表情符号方法添加了一个可选参数:

public function replaceEmoticons($input, $use_emo_encoding_for_regex = true) {

我把前臂的部分稍微改了一下:

foreach ($emo_group['emoticons'] as $emoticon) {
    if ($use_emo_encoding_for_regex === true) {
        $emoticon = htmlspecialchars($emoticon, ENT_QUOTES);
    }
    $regex_emo_part[] = preg_quote($emoticon, '#');
}

它有效!所有表情符号都已替换!