preg_replace not replacing in a Wordpress plugin

一笑奈何 提交于 2019-12-08 08:59:16

问题


In follow-up to my previous question, I want to replace every instance of an ALL-CAPS* word with a link of the following format:

dictionary.com/browse/<TERM>

The preg_replace call I am using is this:

$content = preg_replace('#[A-Z][A-Z]+#', '<a href="//dictionary.com/browse/$1">$1</a>', $content);

Using http://gskinner.com/RegExr, it appears I have my regex correct, and that it should be replacing on each find.

Have I done something wrong, either in the preg_replace call, or pehaps in the registration of the plugin/filter to the Wordpress API?


Full context of the call:

function define_filter($content){
  $content = preg_replace('#[A-Z][A-Z]+#', '<a href="//dictionary.com/browse/$1">$1</a>', $content);
}

add_filter('the_content', 'define_filter');

* I'm using the [A-Z][A-Z]+ syntax to ensure I do not match words like "I" and "A"


回答1:


I believe the function needs to return the result of the replacement:

return $content;

Also, that regex doesn't look right. If you want to match a whole word in all caps, it's

'#\b[A-Z]+\b#'

Also, you want $0 (the whole match), not $1 (the first capture group, which your regex doesn't have)



来源:https://stackoverflow.com/questions/3443207/preg-replace-not-replacing-in-a-wordpress-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!