如果这是输入字符串:
$ input ='在生物学(植物学)中,“水果”是开花的一部分 植物来源于花的特定组织,主要是一种或多种 更多的卵巢。严格地说,这个定义排除了许多结构 这是术语常识中的“果实”,例如那些 由非开花植物产生的;
现在我想对单词 tissue 执行搜索,因此只返回字符串的一部分,由结果所在的位置定义,如下所示:
$ output ='...开花植物来自花的特定组织,主要是一个或多个卵巢......';
搜索词可能在中间。
我如何执行上述内容?
答案 0 :(得分:3)
使用preg_match
替代我的其他答案:
$word = 'tissues'
$matches = array();
$found = preg_match("/\b(.{0,30}$word.{0,30})\b/i", $string, $matches);
if ($found == 0) {
// string not found
} else {
$output = $matches[1];
}
这可能会更好,因为它使用单词边界。
编辑:要使用标记包围搜索字词,您需要稍微更改正则表达式。这应该这样做:
$word = 'tissues'
$matches = array();
$found = preg_match("/\b(.{0,30})$word(.{0,30})\b/i", $string, $matches);
if ($found == 0) {
// string not found
} else {
$output = $matches[1] . "<strong>$word</strong>" . $matches[2];
}
答案 1 :(得分:1)
用户strpos
找到单词的位置,substr
来提取报价。例如:
$word = 'tissues'
$pos = strpos($string, $word);
if ($pos === FALSE) {
// string not found
} else {
$start = $pos - 30;
if ($start < 0)
$start = 0;
$output = substr($string, $start, 70);
}
使用stripos
进行不区分大小写的搜索。