在PHP中,在正则表达式内部使用正则表达式变量

4
我的目标:我正在尝试使用正则表达式从PHP中file_get_contents()调用的混乱响应中检索名称字符串。
以下是我从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个字符长度,同时删除 “name” 字符串并计算字符数?
我的最终目标是:
ubuntu-13.10-desktop-amd64.iso

注意:我曾想过仅删除所有末尾的数字而不是字符计数,然而文件名可能没有有效的扩展名并且将来可能只以数字结尾。
2个回答

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);

不错!不知道是谁点了踩...唯一的补充就是要通过引用传递 $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]);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接