簡體   English   中英

PHP RegEx:如何從句子中提取某些單詞?

[英]PHP RegEx: How to extract certain words from a sentence?

我有一個像這樣的Wikitext:

由David Fincher執導。 由Jim Uhls撰寫。 改編自查克·帕拉紐克(Chuck Palahniuk)的小說。

我正在嘗試制作僅獲取David FincherJim Uhls的正則表達式,這兩個名稱將根據url有所不同。 我做了以下正則表達式,它確實起作用了(替換了不需要的文本之后),還有更好的方法嗎?

/(Directed by)([\w\s]+). (Written by)([\w\s]+). /g

(?:Directed|Written)\\s*by\\s這將與Directed byWritten by

\\K將放棄之前的比賽。

[^\\.]+最多匹配一個字符. 點(不包括.dot)。

正則表達式:/( /(?:Directed|Written)\\s*by\\s+\\K[^.]+/g

正則表達式演示

<?php

ini_set('display_errors', 1);
$string='Directed by David Fincher. Written by Jim Uhls. Based on the novel by Chuck Palahniuk.';
preg_match_all("/(?:Directed|Written)\s*by\s+\K[^.]+/", $string,$matches);
print_r($matches);

輸出:

Array
(
    [0] => Array
        (
            [0] => David Fincher
            [1] => Jim Uhls
        )

)

這是我能想到的最干凈的:

<?php

// https://regex101.com/r/dxft9p/1

$string = 'Directed by David Fincher. Written by Jim Uhls. Based on the novel by Chuck Palahniuk.';
$regex = '#Directed by (?<director>\w+\s?\w+). Written by (?<author>\w+\s?\w+)#';
preg_match($regex, $string, $matches);

echo 'Director - '.$matches['director']."\n";
echo 'Author - '.$matches['author'];

請參閱此處以獲取工作示例https://3v4l.org/AuDL0

當在方括號中使用(?<somelabel> blah)時,將創建一個命名的捕獲組。 非常便利!

暫無
暫無

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

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