在 PHP 中查找关键字前后的单词 [英] find words before and after a keyword in PHP

查看:32
本文介绍了在 PHP 中查找关键字前后的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是搜索一个词(或几个词),然后返回关键字前 5 个词和关键字后 5 个词的字符串.

What i'm trying to do is search for a word (or couple of words) and then return a string of 5 words before, and 5 words after the keyword.

我的PHP代码是这样的:

My PHP code is like this:

function getPreview($keyWord, $searchArea) {
    preg_match("/(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?$keyWord ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)? ?(\w+)?/i", $searchArea, $result);
    foreach ($result as $res) {
        return preg_replace("/$keyWord/", "<B>$keyWord</B>", $res);
        break;
    }
}

唯一的问题是,当之前或之后没有 5 个单词时,PHP 不会返回 this.

The only problem is, when there aren't 5 words before, or after, PHP doesn't return this.

有谁知道我怎样才能更动态地做到这一点?所以 PHP 知道有多少个单词..?

Does anyone know how I can make this more dynamicly? So PHP knows how many words there are..?

谢谢!

推荐答案

我猜这就是你想要的:

$re = '/((\w* ){0,5})(keyWord)(( \w*){0,5})/i'; 
$str = 'klaus steven keyword peter holger und so weiter und so fort'; 

preg_match_all($re, $str, $matches);

它有 0 到 5 次单词后跟空格",然后是您的关键字,然后是另一个空格后跟单词"0 到 5 次.

It has "word followed by space" for 0 to 5 times, then your keyword and then another "space followed by word" for 0 to 5 times.

查看更多信息此处

这篇关于在 PHP 中查找关键字前后的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆