How to split a string in PHP?

3

I need to get two items on the magnet link

magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337

The value after btih :, which is:

0eb69459a28b08400c5f05bad3e63235b9853021

and the values of tr:

udp://tracker.com:80

How do I do this?

    
asked by anonymous 19.04.2014 / 02:25

2 answers

3

Another approach is to use a regex for the string after btih: and use explode() to get all the seeds ( udp://tracker.com:80 )

preg_match('/(?:btih:)+([a-z0-9]+)(?:&dn=)/i', $link, $torrent);
$seeds =  explode('&tr=', $link);

echo 'o torrent: '. $torrent[1] . ' possui os seguintes seeds : <br>';
array_splice($seeds, 0, 1); //remove o primeiro elemento do array

foreach ($seeds as $item){
    echo urldecode($item).'<br>';
}

This eliminates the returned dirt from explode which is: magnet:?xt=urn:btih:0eb69459a28b0840 ...continua because the cut point is &tr= or whatever is on the right also goes to the array.

 array_splice($seeds, 0, 1);

The output of the code:

o torrent: 0eb69459a28b08400c5f05bad3e63235b9853021 possui os seguintes seeds :
udp://tracker.com:80
udp://tracker.publicbt.com:80
udp://tracker.istole.it:6969
udp://tracker.ccc.de:80
udp://open.demonii.com:1337
    
19.04.2014 / 03:52
3

I do not know if it's the best way, but one way would be to use a regular expression:

^.*?btih\:([^&]+).*?tr\=([^&]+).*$

Detailing:

  • ^ - start of string
  • .*? - followed by anything (lazy evaluation)
  • btih\: - followed by string btih:
  • ([^&]+) - followed by anything other than & (first catch group)
  • .*? - followed by anything (lazy evaluation)
  • tr\= - followed by string tr=
  • ([^&]+) - followed by anything other than & (second catch group)
  • .* - followed by anything (greedy evaluation)
  • $ - end of string

Complete code:

$string = "magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337";
$regex = "/^.*?btih\:([^&]+).*?tr\=([^&]+).*$/";
if ( preg_match($regex, $string, $resultados) ) {
    /* $resultados[1] é o valor depois de btih: */
    /* $resultados[2] é o valor do orimeiro tr= */
}

Example in ideone .

    
19.04.2014 / 03:00