Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to use regex to replace all links even relative links with https://snowycinccino.com/iframe/?url=(Old URL here and base of url if it includes) I need it to work with href and src.

What I have tried:

This is my current code:

<?php
$newurl=parse_url($_GET["url"]);
$base=$newurl["scheme"]."://".$newurl["host"]."/";
$basenew=$newurl["scheme"]."://".$newurl["host"];
?>

<?php
$input = $page = file_get_contents($_GET["url"]);

$domain = $base;
$rep['/href="(?!https?:\/\/)(?!data:)(?!#)/'] = 'href="'.$domain;
$rep['/src="(?!https?:\/\/)(?!data:)(?!#)/'] = 'src="'.$domain;
$rep['/@import[\n+\s+]"\//'] = '@import "'.$domain;
$rep['/@import[\n+\s+]"\./'] = '@import "'.$domain;
$output = preg_replace(
    array_keys($rep),
    array_values($rep),
    $input
);

echo $output;
?>
Posted
Updated 24-Feb-18 17:42pm
v2

1 solution

The following example should do the trick, it will replace the content in src and href with the new url.

https://animalfarmxyz.com/iframe/?url=(monkey.aspx)
https://animalfarmxyz.com/iframe/?url=(abc.jpg)
https://animalfarmxyz.com/iframe/?url=(http://www.monkey.com/a2.aspx)
https://animalfarmxyz.com/iframe/?url=(../xxx.jpg)

PHP
<?php

$text = '<a href="/KB/answers/monkey.aspx" </a> abcd
<img src="abc.jpg" other="fssdf" /> ya di ya 
di ya bold<a href="http://www.monkey.com/a.aspx" </a> abcd
<img src="../xxx.jpg" other="fssdf" /> ya di ya 
di ya bold';
$check_hash = preg_match_all("/(?:href|src)=[\"|']?(.*?)[\"|'|>]+/", $text, $hashtweet);
foreach ($hashtweet[1] as $ht){
    $newUrl = 'https://animalfarmxyz.com/iframe/?url=(' . $ht . ')';
  echo $newUrl . '<br/>';
    
  $text = str_replace($ht,$newUrl,$text);
}

echo $text;
?>
 
Share this answer
 
Comments
SkyeEverest 25-Feb-18 1:11am    
Ok, that works, except the (../xxx.jpg) needs to have http://monkey.com/xxx.jpg instead of (../xxx.jpg)
Bryian Tan 25-Feb-18 1:37am    
You might need to write a if statement to handle that scenario.
Bryian Tan 25-Feb-18 1:39am    
You might need to write a if statement to handle that scenario (replace ../ with the http://monkey.com/)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900