如何返回文本的一部分,中间有一个特定的单词


How do I return a part of text with a certain word in the middle?

如果这是输入字符串:

$input = '在生物学(植物学)中,"果实"是开花的一部分源自花的特定组织的植物,主要是一个或更多的卵巢。严格地说,这个定义排除了许多结构这些都是"水果"这个词的常识性,比如那些由非开花植物产生';

现在我想对单词组织执行搜索,因此只返回字符串的一部分,由结果所在的位置定义,如下所示:

$output = '…,主要是一个或多个子房…;

搜索词可能在中间

如何执行上述操作?

我使用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];
}

用户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搜索不区分大小写

相关文章: