如何只在字符串周围提取两个单词并用" ..."?替换其他单词

时间:2015-08-27 06:59:46

标签: php regex string text

我正在尝试围绕特定字符串制作粗体两个单词,如问题How can I bold two words around a string within a string, but not overlap sentences?

解决方案是

$string = preg_replace("/\\b(\\w+ +){0,2}$query( +\\w+){0,2}\\b/i",
                       '<strong>$0</strong>',
                       $string);

哪个适用于我,但是,我想让其他字符串(不是粗体字符串)替换为&#34; ...&#34;例如考虑字符串

$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';
如果我正在搜索&#34;&#34;,那么

可以这样看待

  

... 以及匹配后的字 ......   单词数组的边界   ... 禁用/启用表单元素 ...

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

最后,我们可以设置一个限制,可以找到可以找到的搜索次数,以便再次搜索字符串&#34;&#34;在前面的文字中,我将限制设置为一个我应该得到的

  

... 以及匹配后的字 ......

1 个答案:

答案 0 :(得分:0)

RegEx非常强大,但有时您需要更多代码。 函数sentence_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);

输出:

... 在匹配的单词后 ... 单词数组 ... 的边界,以禁用/启用表单元素 ...

OR

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

输出

... 在匹配的单词后 ... 单词数组的边界 ......

使用第四个参数&#34; $ delimiter&#34;你可以玩。将分隔符设置为emtpy字符串是不可能的,因为它会破坏所需的结果。

但我们都在这里玩:)

我在发帖后看到的问题是字符串&#34;禁用/启用&#34;。对于当前版本的sentence_split,这只是一个词。因此它也输出了之前的单词。将这个视为两个词会使整个事情变得更加复杂。