2013-11-26 89 views
4

我的目标之内:我试图用正则表达式在PHP中一个file_get_contents()呼叫的响应混乱检索名称字符串。从正则表达式本身内使用正则表达式的变量,PHP

这里是我所得到从file_get_contents回电的摘录和字符串我将与合作:

file_get_contents('http://releases.ubuntu.com/13.10/ubuntu-13.10-desktop-amd64.iso.torrent'); 

28:announce39://torrent.ubuntu.com:6969 /announce13:announce-listll39://torrent.ubuntu.com:6969/announceel44://ipv6.torrent.ubuntu.com:6969/announceee7:comment29:Ubuntu CD releases.ubuntu.com13:creation datei1382003607e4:infod6:lengthi925892608e4: name30:ubuntu-13.10-desktop-amd64.iso12:piece lengthi524288e6:pieces35320:I½ÊŒÞJÕ`9

你可以看到我对上面的感兴趣的文字有多大胆。我使用的正则表达式是目前如下:

preg_match('/name[0-9]+\:(.*?)\:/i', $c, $matches); 

这给了我:

name30:ubuntu-13.10-desktop-amd64.iso12 

现在,name30是从下半名称,长度也30个字符冒号,所以我怎样才能使用这个变量继续只有30个字符长度完成正则表达式,同时删除“名称”字符串和计数字符?

我的最终目标将是:

ubuntu-13.10-desktop-amd64.iso 

注:我没想到的只是移除任何最终数字而不是字符计数,但文件名可能没有一个有效的扩展,可能只是在数字结束未来。

回答

3

假设name([0-9]+):是固体寻找你需要什么开始,你可以使用preg_replace_callback

$names = array(); 
preg_replace_callback("/name([0-9]+):(.*?):/i", function($matches) use (&$names){ 
    // Substring of second group up to the length of the first group 
    $names[] = substr($matches[2], 0, $matches[1]); 
}, $c); 
+0

不错!不知道谁downvoted ...只有在这里添加是通过引用传递'$ names'使其工作('&$ names'),但这似乎工作得很好,谢谢! – Jimbo

2

的另一种方式:

preg_match_all('/:name(\d+):\K[^:]+/', $str, $matches, PREG_SET_ORDER); 
foreach ($matches as $match) { 
    $results[] = substr(match[0], 0, $match[1]); 
} 
相关问题