Search code examples
phpregexpreg-replacepreg-matchstr-replace

Replace many code lines in PHP between tags


I have gotten a page php with this line:

$url = file_get_contents('http://web.com/rss.php');

Now I want replace this:

<link>http://web.com/download/45212/lorem-ipsum</link> <link>http://web.com/download/34210/dolor-sit</link> <link>http://web.com/download/78954/consectetur-adipiscing</link> <link>http://web.com/download/77741/laboris-nisi</link>...

With this:

<link>http://otherweb.com/get-d/45212</link> <link>http://otherweb.com/get-d/34210</link> <link>http://otherweb.com/get-d/78954</link> <link>http://otherweb.com/get-d/77741</link>...

I have replaced a part with str_replace but I don't know to replace the other part.

This is what i have done for the moment:

$url = str_replace('<link>http://web.com/download/','<link>http://otherweb.com/get-d/', $url);

Solution

  • You can do this all with a single line of regex :)

    Regex

    The below regex will detect your middle numbered section....

    <link>http:\/\/web\.com\/download\/(.*?)\/.*?<\/link>
    

    PHP

    To use this inside PHP you could use this line of code

    $url = preg_replace("/<link>http:\/\/web\.com\/download\/(.*?)\/.*?<\/link>/m", "<link>http://otherweb.com/get-d/$1</link>", $url);
    

    This should do exactly what you need!

    Explanation

    The way it works is preg_replace looks for <link>http://web.com/download/ at the start and /{something}</link> at the end. It captures the middle area into $1

    So when we run preg_replace ($pattern, $replacement, $subject) we tell PHP to just find that middle part (the numbers in your URLS) and embed them into "<link>http://otherweb.com/get-d/$1</link>".

    I tested it and it seems to be working :)

    Edit: I would propose this answer as best for you as it does everything with a single line, and does not require any str_replace. My answer also will function even if the middle section is alphanumeric, and not only if it is numeric.