【发布时间】:2020-02-10 21:46:31
【问题描述】:
我正在编写一些代码来替换 WordPress 内容中的单词以获取链接。例如:文本链接需要替换“example”一词:<a href="'.$site.'/glossary/example/" class="glossary-link">example</a>。
我已经使用以下代码完成了这项工作:
function word_replace($text){
$site = esc_url( home_url() );
$replace = array(
'example' => '<a href="'.$site.'/glossary/example/" class="glossary-link">example</a>',
'word' => '<a href="'.$site.'/glossary/word/" class="glossary-link">word</a>',
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
}
唯一的问题是 href="" 属性中的单词也会被替换,这会破坏 HTML。如何避免在 href="" 属性或 class="" 属性中替换单词?我需要什么正则表达式来跳过这些属性?一段示例代码将是一个很大的帮助:-)
【问题讨论】:
-
php regex to match outside of html tags 的可能重复项。如果您想通过正则表达式执行此操作,我建议您使用this answer
-
嗨@bobblebubble,感谢您回答我的问题以及此解决方案的链接。我实际上正在寻找与此相反的答案。在此评论 (stackoverflow.com/a/7891998/7735516) 中,除了链接(HTML a 标签)外,所有内容都被跳过。我想替换 WordPress 内容 ($text) 内的数组中的任何单词,但跳过 HTML a 标签。我如何做到这一点?
-
你的意思是外部标签,对吧?见this at regex101。如果不是
<inside>,它匹配foo和bar。
标签: php regex wordpress replace preg-replace