簡體   English   中英

提取兩個單詞之間的字符串

[英]Extract a string between two words

我想從下面的字符串中提取哈希,即e5e1af55bad959546ec7608cc8685fe67bc5426e

$word1 = 'btih:';
$word2 = '&dn';
$magnet = "[magnet:?xt=urn:btih:e5e1af55bad959546ec7608cc8685fe67bc5426e&dn=The+Deadly+Game+2013+DVDRip+XviD-EVO+&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337]";
if(preg_match('/'.preg_quote($word1).'(.*?)'.preg_quote($word2).'/is', $magnet, $match)){
$upper = strtoupper($match['1']);
$generated = "http://torrage.com/torrent/".$upper.".torrent";
}

在上面的代碼中,哈希位於btih:之間btih:&dn我可以知道為什么我的代碼不起作用嗎?

您可以使用這種基於環顧的正則表達式:

'/(?<=btih:)(.+?)(?=&dn=)/'

這意味着捕獲一個在bith:之前和&dn=之后的字符串

另外,您可以避免后顧之憂並使用:

'/:btih:\K(.+?)(?=&dn=)/'

這里\\K用於重置匹配的模式。

作為另一種選擇,您也可以避免lookahead並使用:

'/:btih:(.+?)&dn=/'

並使用匹配的group #1

暫無
暫無

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

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