php - 提取单词前后的部分字符串

标签 php regex string search

我需要提取并在查询词之前之后显示一些词,比如谷歌搜索结果,例如:

$str = "hi user! welcome to new php open source world, we are trying to learn you something!";
$query = "new php";
$result = "... welcome to new php open source ...";

我搜索了 google 和 SO 但没有找到明确的答案,或者我的 php 知识还不够! 是否有可行且易于使用的功能来完成这项工作?

最佳答案

function yourFuncName($str, $query, $numOfWordToAdd) {
    list($before, $after) = explode($query, $str);

    $before = rtrim($before);
    $after  = ltrim($after);

    $beforeArray = array_reverse(explode(" ", $before));
    $afterArray  = explode(" ", $after);

    $countBeforeArray = count($beforeArray);
    $countAfterArray  = count($afterArray);

    $beforeString = "";
    if($countBeforeArray < $numOfWordToAdd) {
        $beforeString = implode(' ', $beforeArray);
    }
    else {
        for($i = 0; $i < $numOfWordToAdd; $i++) {
            $beforeString = $beforeArray[$i] . ' ' . $beforeString; 
        }
    }

    $afterString = "";
    if($countAfterArray < $numOfWordToAdd) {
        $afterString = implode(' ', $afterArray);
    }
    else {
        for($i = 0; $i < $numOfWordToAdd; $i++) {
            $afterString = $afterString . $afterArray[$i] . ' '; 
        }
    }

    $string = $beforeString . $query . ' ' . $afterString;

    return $string;
}

输出是: user!欢迎来到新的 php 开源世界, ($numOfWordToAdd = 3)

关于php - 提取单词前后的部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12629081/

相关文章:

php - 是否有可以清理内容的 PHP 类?

c# - 如何访问 .NET Regex 中的命名捕获组?

Java Buffered reader 堆空间不足

php - "unauthorized_client"使用 PHP 客户端通过 Google API 客户端刷新 token 时出错?

php - A 类的对象随意(不总是)继承 B 类的行为,同时保留自己的行为。可能的?

php - 在 php 中获取类型返回 "object"而不是对象类型

python - 从字符串中提取要列出的元素时遇到问题

在 Swift iOS 中解码 PHP JSON 返回空值

regex - 大文件中带有反向引用的多行搜索

c++ - 使用strupr和strlwr时报错 "invalid conversion of char to char*"如何解决?