【发布时间】:2020-07-07 16:51:51
【问题描述】:
我有以下preg_replace
foreach ($financeTermsArray as $term => $info) {
$content = preg_replace($term, $info, $content, 1);
}
$info 变量的样子
'<a class="glossar-word" href="' . get_permalink() . '" data-glossar="' . $excerpt . '">' . get_the_title() . '</a>';
和$term 变量如"/\b" . get_the_title() . "\b/"
如果匹配的单词在data-glossar html 属性中,我想从preg_replace 中排除。
我该怎么做?
我得到了它使用以下模式:
"/data-glossar=\"([^\"]*)(*SKIP)(*F)|\b" . get_the_title() . "\b/"
【问题讨论】:
-
正则表达式在哪里?
-
matched word等于从get_the_title()返回的内容因此,您必须将get_the_title()返回的内容合并到一个正则表达式中,该正则表达式跳过包含data-glossar属性中的该值的标签.那是你要的吗 ?还是您需要先排除所有标签? -
是的,因为
$content正在更新循环匹配,并且数据属性值可能包含关键字,在这种情况下应该跳过。 -
I want to exclude from preg_replace if matched word is inside data-glossar html attribute.和I got it working with the following pattern:实际上该模式在技术上与该属性不匹配,因为它不是标签/属性正则表达式。我的正则表达式排除了所有 html,因此它永远不会失败,也永远不会有歧义。如果我给了你SKIP/FAIL的想法,你能接受并支持我的回答吗? -
顺便说一句,为了安全起见,
"\b/"应该是"\\b/"。
标签: php regex preg-replace