【问题标题】:Can Regex/preg_replace be used to add an anchor tag to a keyword?可以使用 Regex/preg_replace 为关键字添加锚标记吗?
【发布时间】:2009-01-03 20:48:58
【问题描述】:

我希望能够切换这个...

My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this keyword here.

到...

My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this [a href="url"]keyword[/a] here.

我不能简单地替换“关键字”的所有实例,因为有些是在现有锚标记中或内部使用的。

注意:在 Linux 上使用 PHP5 preg_replace。

【问题讨论】:

    标签: php regex


    【解决方案1】:

    使用正则表达式可能不是解决这个问题的最佳方法,但这里有一个快速的解决方案:

    function link_keywords($str, $keyword, $url) {
        $keyword = preg_quote($keyword, '/');
        $url = htmlspecialchars($url);
    
        // Use split the string on all <a> tags, keeping the matched delimiters:
        $split_str = preg_split('#(<a\s.*?</a>)#i', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
    
        // loop through the results and process the sections between <a> tags
        $result = '';
        foreach ($split_str as $sub_str) {
            if (preg_match('#^<a\s.*?</a>$#i', $sub_str)) {
                $result .= $sub_str;
            } else {
                // split on all remaining tags
                $split_sub_str = preg_split('/(<.+?>)/', $sub_str, -1, PREG_SPLIT_DELIM_CAPTURE);
                foreach ($split_sub_str as $sub_sub_str) {
                    if (preg_match('/^<.+>$/', $sub_sub_str)) {
                        $result .= $sub_sub_str;
                    } else {
                        $result .= preg_replace('/'.$keyword.'/', '<a href="'.$url.'">$0</a>', $sub_sub_str);
                    }
                }
            }
        }
        return $result;
    }
    

    一般的想法是将字符串拆分为链接和其他所有内容。然后将链接标签之外的所有内容拆分为标签和纯文本,并将链接插入纯文本中。这将阻止 [p class="keyword"] 扩展到 [p class="[a href="url"]keyword[/a]"]。

    再次,我会尝试找到一个不涉及正则表达式的更简单的解决方案。

    【讨论】:

      【解决方案2】:

      您不能仅使用正则表达式来做到这一点。正则表达式是上下文无关的——它们只是匹配一个模式,而不考虑周围环境。为了做你想做的事,你需要将源解析为抽象表示,然后将其转换为目标输出。

      【讨论】:

      • 不能使用“lookahead”和“lookbehind”功能来解释匹配模式的周围环境吗?
      • 您也许可以使用环视,但这会非常困难。我建议您查看 preg_replace_callback。搜索完整的锚元素或关键字。如果匹配锚元素,请将其重新插入;如果您匹配一个裸关键字,请添加标签。
      猜你喜欢
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多