简体   繁体   English

提取两个单词之间的字符串

[英]Extract a string between two words

I want to extract hash from string below which is e5e1af55bad959546ec7608cc8685fe67bc5426e 我想从下面的字符串中提取哈希,即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";
}

in above code, the hash are located between btih: and &dn can i know why my code doesnt work? 在上面的代码中,哈希位于btih:之间btih:&dn我可以知道为什么我的代码不起作用吗?

You can use this lookaround based regex: 您可以使用这种基于环顾的正则表达式:

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

This means capture a string which is preceded by bith: and followed by &dn= 这意味着捕获一个在bith:之前和&dn=之后的字符串

Alternatively you can avoid lookbehind and use: 另外,您可以避免后顾之忧并使用:

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

Here \\K is used to reset matched pattern. 这里\\K用于重置匹配的模式。

As an another alternative you can avoid lookahead also and use: 作为另一种选择,您也可以避免lookahead并使用:

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

And use matched group #1 并使用匹配的group #1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM