【问题标题】:How to extract only two words around string and replace the others by "..."?如何仅提取字符串周围的两个单词并用“...”替换其他单词?
【发布时间】:2015-11-21 10:33:24
【问题描述】:

我正在尝试在特定字符串周围加粗两个单词,例如问题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);

这对我来说很好,但是,我想将其他字符串(非粗体)替换为“...”,例如考虑字符串

$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”时,我将限制设置为我应该只得到一个

... 在匹配词之后 ...

【问题讨论】:

标签: php regex string text


【解决方案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 的当前版本,这是一个词。因此它也输出之前的单词。将其视为两个词会使整个事情变得更加复杂。

【讨论】:

  • 这很好,但它仅在您搜索两个空格之间的单词或字符串时有效,例如,如果您搜索单词“sentence”,您将得到两个结果但是如果您搜索“sent”或“entenc”或“sentence int”你不会得到任何结果。这可以解决吗?
  • 通过一些额外的工作可以解决这个问题!但是,我提供的功能首先满足您的要求。我认为只使用正则表达式就很难分割没有空格!为什么投反对票?
猜你喜欢
  • 2016-11-24
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 2012-04-13
相关资源
最近更新 更多