Php 如何仅提取字符串周围的两个单词,并将其他单词替换为“&引用;?

Php 如何仅提取字符串周围的两个单词,并将其他单词替换为“&引用;?,php,regex,string,text,Php,Regex,String,Text,我试着用两个粗体字围绕着一个特定的字符串,就像上面讨论的那样 解决方案如下所示: $string = preg_replace("/\\b(\\w+ +){0,2}$query( +\\w+){0,2}\\b/i", '<strong>$0</strong>', $string); 如果我在搜索“the”这个词,这个词是否可以被视为 并在匹配的单词之后。。。 单词数组的边界 …禁

我试着用两个粗体字围绕着一个特定的字符串,就像上面讨论的那样

解决方案如下所示:

$string = preg_replace("/\\b(\\w+ +){0,2}$query( +\\w+){0,2}\\b/i",
                       '<strong>$0</strong>',
                       $string);
如果我在搜索“the”这个词,这个词是否可以被视为

并在匹配的单词之后。。。 单词数组的边界禁用/启用表单元素

此解决方案的另一个缺点是,它只搜索两个空格之间的字符串。是否可以修改它以搜索任何字符串

最后,我们能否对可以找到的搜索数量设置一个限制,这样,如果我们再次搜索上一个文本中的字符串“the”,并且我将限制设置为我只能得到的一个

并在匹配的单词之后


RegEx功能强大,但有时需要更多的代码。 函数
语句\u split
将执行您想要的操作

$string = 'Then split that sentence into words and add some tags in two words before and after the matching word. 
Since you only have one sentence to work on, you\'d include a check to make sure you didn\'t go out of bounds of the word array.
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute';
$query = "the";


function sentence_split($text, $query, $limit = null, $delimiter=" "){
    preg_match_all("/\b([\/\w]+$delimiter){0,2}$query($delimiter\w+){0,2}\b/i", $text, $result);
    if(!is_null($limit)){
    $result[0] = array_slice($result[0], 0, $limit);    
    }
    return "... <strong>".implode($result[0],"</strong> ... <strong>") . "</strong> ...";
}


var_dump(sentence_split($string, $query);
输出

并在匹配的单词之后单词数组的边界

有了第四个参数“$delimiter”,您就可以到处玩了。不太可能将delimiter设置为emtpy string,因为它会破坏所需的结果

但我们都在这里玩:)


发布后我看到的问题是字符串“disable/enable”。对于当前版本的
句子\u split
这是一个单词。因此,它还输出单词before。把这当作两个词会使整个事情变得更加复杂。

不确定,但也许。或者。使用
preg_match
@stribizhev将搜索限制为1,您的两个建议都给出了
警告:preg_replace()至少需要3个参数,2个参数在…
中给出,不知道您是如何测试的,但既然您感兴趣,这里是。使用这个正则表达式而不是
禁用/启用表单元素
,如果表单元素设置为匹配
/
,您将获得
禁用/启用表单元素
。这对您来说是个问题吗?这很好,但它仅在两个空格之间搜索单词或字符串时有效,例如,如果您搜索单词“句子”,你会得到两个结果,但是如果你搜索“sent”或“entenc”或“句子int”,你将不会得到任何结果。这是可以解决的吗?通过一些额外的工作,这是可以解决的!但是我提供的函数满足了你最初的要求。没有空格的拆分将非常困难,我想只有正则表达式!为什么要否决?
$string = 'Then split that sentence into words and add some tags in two words before and after the matching word. 
Since you only have one sentence to work on, you\'d include a check to make sure you didn\'t go out of bounds of the word array.
Sometimes you need to disable/enable the form element like input or textarea. Jquery helps you to easily make this with setting disabled attribute';
$query = "the";


function sentence_split($text, $query, $limit = null, $delimiter=" "){
    preg_match_all("/\b([\/\w]+$delimiter){0,2}$query($delimiter\w+){0,2}\b/i", $text, $result);
    if(!is_null($limit)){
    $result[0] = array_slice($result[0], 0, $limit);    
    }
    return "... <strong>".implode($result[0],"</strong> ... <strong>") . "</strong> ...";
}


var_dump(sentence_split($string, $query);
var_dump(sentence_split($string, $query, 2);