簡體   English   中英

如何在中間返回帶有特定單詞的部分文本?

[英]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查找word和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進行不區分大小寫的搜索。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM