如何提取字符串周围的两个单词,并将其他单词替换为“……”


How to extract only two words around string and replace the others by "..."?

我正试图在一个特定的字符串周围加粗两个单词,就像在问题中我怎么能在字符串内的字符串周围加粗两个单词,但不重叠的句子?

解为

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

这对我来说很好,然而,我想让其他字符串(不是粗体的)被"…"取代,例如考虑字符串

$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';

如果我要搜索单词"the",它是否看起来像

和匹配字后面…数组的边界...禁用/启用表单元素

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

最后,我们是否可以对可以找到的搜索次数设置一个限制,以便如果再次搜索前一个文本中的字符串"the"并且我将限制设置为1,则只能得到

和匹配字后面…

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);

输出:

和匹配字后面…字数组禁用/启用表单元素

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

输出

和匹配字后面…字数组

对于第四个参数"$delimiter",您可以随意使用。将分隔符设置为空字符串是不太可能的,因为它会破坏期望的结果。

但我们都在这里玩:)

张贴后我看到的问题是字符串"禁用/启用"。对于sentence_split的当前版本,这是一个单词。因此,它也输出前面的单词。