Php 忽略regex/preg_replace函数中字符串内的css

Php 忽略regex/preg_replace函数中字符串内的css,php,regex,Php,Regex,我编写了以下代码来链接我博客文章中的所有hashtag: function HashTags($string){ global $post_userid; return preg_replace( '/\s*#([a-zA-Z0-9\-_]+)/i', " <a href=\"blog.php?id=".$post_userid."&search=$1\">#$1</a>", $string

我编写了以下代码来链接我博客文章中的所有hashtag:

function HashTags($string){
    global $post_userid;
    return preg_replace(
        '/\s*#([a-zA-Z0-9\-_]+)/i',
        " <a href=\"blog.php?id=".$post_userid."&search=$1\">#$1</a>",
        $string
    );
}
函数HashTags($string){
全局$post_用户ID;
返回预更换(
“/\s*#”([a-zA-Z0-9\-\\+)/i”,
" ",
$string
);
}
它的工作原理很棒!但是问题是,如果在同一个字符串中有一些CSS代码,这个函数也会转换CSS

例:

你好,世界
我的问题是:有没有可能用我的正则表达式函数忽略css,以避免把#fff也变成链接…

我有个主意

  • 删除带标签的所有标签
  • 搜索并查找结果文本中所有哈希标记的关键字
  • 将找到的关键字存储在临时列表中
  • 根据需要使用函数替换所有关键字
  • 诸如此类:

    function HashTags($string){
        global $post_userid;
        $tmp = strip_tags($string);
        preg_match_all('/\s*#[a-zA-Z0-9\-_]+/i', $tmp, $matches);
        foreach ($matches as $match) {
            $string = str_replace(
                $match,
                " <a href=\"blog.php?id=".$post_userid."&search=" . substr($match[0],1) . "\">$match[0]</a>",
                $string
            );
        }
        return $string;
    }
    
    函数HashTags($string){
    全局$post_用户ID;
    $tmp=带标签($string);
    preg_match_all('/\s*#[a-zA-Z0-9\-+/i',$tmp,$matches);
    foreach($matches作为$match进行匹配){
    $string=str\u replace(
    $match,
    " ",
    $string
    );
    }
    返回$string;
    }
    

    它不是很干净,但是你可以把它弄干净。

    你可以预先编写例如
    ]*>(*SKIP)(*F)
    来跳过
    (),但是用正则表达式解析html通常是个坏主意。非常感谢!真是太棒了。。。你能解释一下为什么这是个坏主意吗?@guillermoesquivelobergón在哈希标记的关键字前使用<来了解原因。如果用户希望在文本中使用<,则没有限制!尽管如果文本来自html编辑器或类似的东西,<可能会被转换为@GuillermoEsquivelObregón如果不解析您自己的html,而是任何您不知道会发生什么的任意html,这是个坏主意。另请参见已尝试但此解决方案仍存在问题:如果用户想要发布#FFF hashtag,并且有一个div或另一个带有颜色的html标记:#FFF@GuillermoEsquivelObreg所以你可能会对用户输入施加一些限制,因为如果没有限制,用户可能会选择在他(她)输入的文本中添加内容,等等。
    function HashTags($string){
        global $post_userid;
        $tmp = strip_tags($string);
        preg_match_all('/\s*#[a-zA-Z0-9\-_]+/i', $tmp, $matches);
        foreach ($matches as $match) {
            $string = str_replace(
                $match,
                " <a href=\"blog.php?id=".$post_userid."&search=" . substr($match[0],1) . "\">$match[0]</a>",
                $string
            );
        }
        return $string;
    }