Php 将前三个单词用一个空格括起来

Php 将前三个单词用一个空格括起来,php,wordpress,wordpress-theming,Php,Wordpress,Wordpress Theming,我想过滤_内容,将第一段的前三个单词包装在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');

我想过滤_内容,将第一段的前三个单词包装在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');
函数第一段($content){
if(is_single()){
返回preg_replace('regex在这里',“$1”,$content,1);
}
}
添加过滤器(“内容”、“第一段”);
到目前为止,我还没有找到任何与第一段前三个单词匹配的正则表达式和替换词

有什么帮助吗

谢谢

就像这样:

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.
php>$content='敏捷的棕色狐狸跳过了懒狗';
php>echo preg_replace('/^((\S+\S+{2}\S+/')、'$1',$content);
那只敏捷的棕色狐狸跳过了那只懒狗。
所以,你会想要这个:

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){
if(is_single()){
返回preg_replace('/^((\S+\S+{2}\S+/'),“$1”,$content,1);
}
}
添加过滤器(“内容”、“第一段”);

请记住,如果
$content
少于四个单词,则正则表达式将不匹配,也不会进行替换。

感谢您的回复,但不幸的是,它无法正常工作。它适用于您的示例,但不适用于包装在标记中的内容,如_content()输出的内容:(它到底在做什么?也许如果你能为
$content
提供一个示例值,我可以为你提供一个有效的解决方案。嘿,多西!输出是一个正常的段落,像这样:一些很酷的文本放在这里。

谢谢!@friedsurf-对,所以
$content='一些很酷的文本放在这里。

echo preg\u替换('/^((\S+\S+{2}\S+/','$1',$content);
输出
这里有一些很酷的文本。

-是的,这对于正则表达式来说确实不是一个好任务。