如何在PHP中创建例程直接链接?

Friends, I need help to create a routine (function) in php to solve the hypothetical link below. But I'm not sure where to start:

The initial link captured by preg_match_all is in the format:

http://www.exemplo.br/test.html

What you send to:

http://www.page1.br/sub/exemplo1.php?txt=texto12

In the previous link you need to click on the advertisement 3 times to have access to the ads4 (below). Only in the source code of ads4 is the direct link.

ads1 - http://ad.net/sub/exemplo1.php?txt=texto12
ads2 - http://test.in/sub/exemplo1.php?txt=texto12
ads3 - http://outro.bz/sub/exemplo1.php?txt=texto12
ads4 - http://exemplo.com/sub/exemplo1end.php?txt=texto12

Direct link available in ads4 source code:

http://www.end.com/sub/exemplo1/texto12.txt

I could convert the first link at the end, but I'm lost in how to do a routine that exits from where I am (preg_match_all link) to the text12.txt

http://www.page1.br/sub/exemplo1.php?txt=(.*?)
http://exemplo.com/sub/exemplo1end.php?txt=($1)