Sara
Sara

Reputation:

preg_replace change img and link paths to use proxy

I've run into a hard problem to deal with. I am replacing a-tags and img-tags to fit my suggestions like this. So far so good.

$search = array('|(<a\s*[^>]*href=[\'"]?)|', '|(<img\s*[^>]*src=[\'"]?)|');
$replace = array('\1proxy2.php?url=', '\1'.$url.'/');
$new_content = preg_replace($search, $replace, $content);

Now my problem is that there are links on pages that i fetch the content of that looks like this:

<a href="/test/page/">

and

<a href="http://google.se/test/">

And when after replacing these two links looks like this:

<a href="proxy2.php?url=/test/page/">

and

<a href="proxy2.php?url=http://google.se/test/">

The problem is for me is that i want to include a variable named $url before /test/page/ and only on that links that are like that, not those who was already http:// or https:// before.

Upvotes: 2

Views: 2301

Answers (4)

Sara
Sara

Reputation:

it's me Sara. Scronide, your code did'nt work. It still returns:

<a href="proxy2.php?url=/test/page/">
<a href="proxy2.php?url=google.se/test/">

Instead of what i wanted it to show, i wanted it to show like this, with the url prepended:

<a href="proxy2.php?url=**THEURLHERE.COM**/test/page/">
<a href="proxy2.php?url=google.se/test/">

SORRY, IT DID WORK, I WAS DOING SOMETHING WRONG WITH THE URL VARIABEL. THANK U SCRONIDE!

Upvotes: 0

scronide
scronide

Reputation: 12248

This should do the job for the anchor tags, at least:

<?php
function prepend_proxy($matches) {
    $url = 'http://example.prefix';

    $prepend = $matches[2] ? $matches[2] : $url;
    $prepend = 'proxy2.php?url='. $prepend;

    return $matches[1] . $prepend . $matches[3];
}
$new_content = preg_replace_callback(
    '|(href=[\'"]?)(https?://)?([^\'"\s]+[\'"]?)|i',
    'prepend_proxy',
    $content
);
?>

Upvotes: 2

bisko
bisko

Reputation: 4078

This would do the trick

$search = array('@(<a\s*[^>]*href=[\'"]?)(https?://)?@');
$replace = array('\1proxy2.php?url=');
$new_content = preg_replace($search, $replace, $content);

Result:

<a href="proxy2.php?url=/test/page/">
<a href="proxy2.php?url=google.se/test/">

Upvotes: 0

Derek Illchuk
Derek Illchuk

Reputation: 5658

Simply make your proxy2.php a little smarter. If a fully qualified URL comes in (http://...), redirect to that. If a local URL comes in (e.g. /test/page/), drop in what's missing (e.g. http://www.mylittleapp.com/test/page/) and redirect.

Upvotes: 0

Related Questions