加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中使用正则表达式本身内的正则表达式变量

发布时间:2020-12-13 17:25:54 所属栏目:PHP教程 来源:网络整理
导读:My goal: I’m trying to use regex to retrieve a name string from the jumbled response of a file_get_contents() call within PHP. 这是我从file_get_contents调用中得到的内容的摘录,以及我将使用的字符串: file_get_contents('http://releases.ubunt

My goal: I’m trying to use regex to retrieve a name string from the jumbled response of a file_get_contents() call within 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?ê?TJ?`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

注意:我确实想过只删除任何结束数而不是字符计数,但是文件名可能没有有效的扩展名,并且可能在将来以数字结尾.

解决方法

假设名称([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],$matches[1]);
},$c);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读