我想檢索圍繞鏈接的整個句子,以標點符號分隔(例如 . 或 ! 或 ? 或換行符)。
目的是為鏈接提供更好的背景關系。
所以例如,如果我有這個......
$input = "I don't want this piece! This is the <a href='https://example.com/my-sentence'>sentence</a> I want. In don't want this piece either";
$filter = "https://example.com/my-sentence";
......我需要解決這個......
$output = "This is the sentence I want.";
到目前為止,我設法隔離了一個不包含標簽的句子,如下所示:
$input = "I don't want this piece. This is the sentence I want. In don't want this piece either";
$filter = "sentence";
$regex = '/[A-Z][^\\.;]*('.$filter.')[^\\.;]*/';
if (preg_match($regex, $input, $match))
$output = $match[0];
這作業得很好。接下來,我不知道如何繞過 url 中的標點符號。
我首先探索了隔離錨點并對其進行正則運算式,這適用于任何單個示例,但可能會在野外產生沖突(錨點復制其他錨點或隨機文本)。
另一種方法似乎是strip_tags,類似于......
$input = strip_tags($input);
......問題是我需要同時剝離和不剝離它們。
也許更具體的正則運算式或函式的一些智能包裝可以帶來一種簡單的方法來解決這個問題,或者它可能是一個死胡同并且需要其他一些方法,我不知道,但現在我被卡住了,請幫忙!
uj5u.com熱心網友回復:
假設您不關心縮寫,您可以在特定過濾器字串之前和之后匹配除?, !and以外的字符.或類似鏈接的子字串零次或多次:
$input = "I don't want this piece! This is the <a href='https://example.com/my-sentence'>sentence</a> I want. In don't want this piece either";
$filter = "sentence";
$regex = '~\b(?:[^.?!]|https?://[^<>\s"\'] )*?'.preg_quote($filter, '~').'(?:[^.?!]|https?://[^<>\s"\'] )*~u';
if (preg_match_all($regex, $input, $match)){
print_r( array_map(function($x) {return strip_tags($x);}, $match[0]) );
}
請參閱PHP 演示。輸出:
Array
(
[0] => This is the sentence I want
)
請參閱正則運算式演示。詳情:
\b- 一個詞的邊界(?:[^.?!]|https?://[^<>\s"\'] )*?- 出現零次或多次(盡可能少)除.,?和!或之外的字符http,可選的s,://然后出現一個或多個除<,>、空格、"、'sentence- 過濾字串(?:[^.?!]|https?://[^<>\s"\'] )*-零個或多個,盡可能多的,無論以外的炭的.,?和!或http,可選的s,://然后比其它一個或多個字符<,>,空格",'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/389451.html
