忽略正则表达式中特定单词组合之间的单词(词汇表链接植入)

问题描述 投票:0回答:1

我已经编辑了我的问题并简化了它。

我创建了一个突出显示文本中词汇表的函数,该函数可用于突出显示共轭单词(法语)。我工作得很好,但我想忽略已经突出显示的单词。所以我需要一种方法来忽略让说之间的任何单词(我简化了它)

有人可以编辑我的正则表达式,使其忽略这些标签之间的单词吗?

这是我的函数的重要部分:

// example glossary but the real one has 10,000 entries
$words = ["example","ample"];
$content = "Here is an example for you."

foreach($words as $word) {
  ///// ***** HERE IS THE PROBLEMATIC REGEX.  The esxu is for french conjugaison *****
  $search = "/([\s\x{00A0} ,\.-;-\(\)\"\'>])(" . $word  . ")([esxu]{0,3})([\s\x{00A0} ,\.;\"--\)\(<])/iu";

  $content = preg_replace_callback($search, function ($words) {
      return $words[1] . '<tag>' . $words[2] .  $words[3] . '</tag>' . $words[4];
    } , $content );
   }
}

目前我会得到

Here is an <tag>ex<tag>ample</tag></tag> for you.

但是我想要

Here is an <tag>example</tag> for you.

所以我需要一些正则表达式模式来说明是否存在:

<tag>XXX</tag>

在搜索后续搜索时忽略XXX(此处为“充足”搜索)。

php regex highlight preg-replace-callback glossary
1个回答
0
投票

为了确保您的正则表达式仅通过一次,请将所有单词内爆到管道子模式中。请务必将较长的“单词”排在较短的“单词”之前,以便较短的匹配项不会在较大的匹配项之前匹配。

您不需要

preg_replace_callback()
,因为您没有在替换参数中进行任何函数调用。

我的肉眼无法判断那些重复的连字符是否唯一,也不知道您的意图是匹配字面连字符还是创建字符范围。如果您打算匹配字符类中的连字符,请将它们移至末尾以消除歧义。

代码:(演示

$words = ["example", "ample"];
$content = "Here is an example for you.";

$regex = "#[\s\x{00A0} ,.;()\"'>-]\K(" . implode('|', array_map('preg_quote', $words))  . ")[esxu]{0,3}(?=[\s\x{00A0} ,.;\"-)(<])#iu";

echo preg_replace($regex, '<tag>$0</tag>', $content);
// Here is an <tag>example</tag> for you.
© www.soinside.com 2019 - 2024. All rights reserved.