首页 > 解决方案 > 将前三个单词包裹在一个跨度中

问题描述

我想过滤 the_content 以将第一段的前三个单词包装在 span 标记中。到目前为止,这是我的代码:

function first_paragraph($content) {
   if(is_single()) {
      return preg_replace('regex goes here', "<p><span>$1</span>", $content, 1);
   }
}

add_filter('the_content', 'first_paragraph');

到目前为止,我没有找到任何匹配第一段前三个单词的正则表达式和替换。

有什么帮助吗?

谢谢!

标签: phpwordpresswordpress-theming

解决方案


像这样:

php > $content = 'The quick brown fox jumped over the lazy dog.';
php > echo preg_replace('/^((\S+\s+){2}\S+)/', '<span>$1</span>', $content);
<span>The quick brown</span> fox jumped over the lazy dog.

所以,你会想要这个:

function first_paragraph($content) {
   if(is_single()) {
      return preg_replace('/^((\S+\s+){2}\S+)/', "<p><span>$1</span>", $content, 1);
   }
}

add_filter('the_content', 'first_paragraph');

请记住,如果$content少于四个单词,则正则表达式将不匹配并且不会发生替换。


推荐阅读