Using regex variable from regex itself, inside PHP

My goal: I am trying to use a regular expression to extract a name string from a mixed call response file_get_contents()in PHP.

Here is an excerpt from what I get from the call file_get_contents, and the line with which I will work:

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: creating datei1382003607e4: infod6: lengthi925892608e4: name30: ubuntu-13.10-desktop-amd64.iso12 : part lengthi524288e6: pieces 35320: I½ÊŒÞJÕ`9

You can see how I encouraged the text of interest. I use regex:

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

This gives me:

name30:ubuntu-13.10-desktop-amd64.iso12

Now name30 is the name, as well as 30 characters in length from the next half-replication, so how can I use this variable to continue for only 30 characters in length until the regular expression ends, deleting the string "name" and the number of characters?

My ultimate goal:

ubuntu-13.10-desktop-amd64.iso

Note. I thought about simply deleting any trailing numbers instead of counting characters, however the file name may not have a valid extension and may end with numbers in the future.

+4
source share
2 answers

Assuming it name([0-9]+):is hard to find the beginning of what you need, you can usepreg_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);
+3
source

Another way:

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

All Articles