4

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.

Here's an excerpt of what I get back from a file_get_contents call, and the string I will be working with:

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

You can see how I've emboldened the text of interest above. The regex I'm using is currently as follows:

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

This gives me:

name30:ubuntu-13.10-desktop-amd64.iso12

Now, name30 is the name and also 30 characters in length from the next semi-colon, so how can I use this variable to continue on for only 30 characters length before finishing the regex, whilst removing the "name" string and count characters?

My end goal would be:

ubuntu-13.10-desktop-amd64.iso

Note: I did think of just removing any end numbers instead of character counting, however the filename may not have a valid extension and may just end with numbers in the future.

2 Answers 2

3

Assuming that name([0-9]+): is solid for finding the start of what you need, you could use 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! No idea who downvoted... Only addition here is to pass $names by reference to make it work (&$names), but that seems to work perfectly, thank you!
2

An other way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.