How to split a string in PHP?

Asked

Viewed 204 times

3

I need to pick up two items on the link Magnet

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 that ?

  • you need all the values after tr= or only first?

  • all values, I need to add them...

2 answers

3

I don’t know if it’s the best way, but one way would be to use a regular expression:

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

Detailing:

  • ^ - string start
  • .*? - followed by anything (lazy assessment)
  • btih\: - followed by the string btih:
  • ([^&]+) - followed by anything other than a & (first catch group)
  • .*? - followed by anything (lazy assessment)
  • tr\= - followed by the string tr=
  • ([^&]+) - followed by anything other than a & (second catch group)
  • .* - followed by anything (greedy assessment)
  • $ - 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 the ideone.

3


Another approach is to use a regex for the string after btih: and use explode() to catch 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 of explode that is:magnet:?xt=urn:btih:0eb69459a28b0840 ...continua because the point of cutting is &tr= or whatever is right also goes to the array.

 array_splice($seeds, 0, 1);

The exit from 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.