提取单词前后字符串的一部分 [英] extract part of a string before and after a word
本文介绍了提取单词前后字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要提取并显示一些词before和after一个查询词,比如谷歌搜索结果,例如:
i need to extract and show some words before and after a query word, something like google search results, for example:
$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 知识还不够!是否有可行且易于使用的功能来完成这项工作?
i searched google an SO but didn't find a clear answer or maybe my php knowledge was not enough! is there a workable and easy-to-use function to do this job?
推荐答案
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)
这篇关于提取单词前后字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文