1

I want to replace all external url except my website link in my article . So that original link to the external site is get encrypted/ masked/ rewritten.

For example:

original link: www.google.com rewrite it to: www.mydomain.com/goto/google.com

I tried DOMDocument and it has error:

Warning: DOMDocument::loadHTML(): Attribute target redefined in Entity, line: 1 in [...][...] on line 20

I tried

<?php
 $html ='1224 <a href="http://www.google.com">google</a> 567';
$tracking_string = 'http://example.com/goto/';
$html = preg_replace('#(<a[^>]+href=")(http|https)([^>" ]+)("?[^>]*>)#is','\\1'.$tracking_string.'\\2\\3\\4',$html);
echo $html; 

it replaces all links including my website links

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
thanh
  • 63
  • 1
  • 8

1 Answers1

0

I'm not very knowledgeable when it comes to RegEx, but after some searching it seems like all you need is a Negative Lookahead.

Regex: #(?!.+(\bgoogle.com\b))(<a[^>]+href=")(http|https)([^>" ]+)("?[^>]*>)#is

<?php
    $html = '1224 <a href="http://www.google.com">google</a> 567';
    $tracking_string = 'http://example.com/track.php?url=';
    $html = preg_replace('#(?!.+(\bgoogle.com\b))(<a[^>]+href=")(http|https)([^>" ]+)("?[^>]*>)#is', '\\2'. $tracking_string.'\\3\\4\\5',$html);
    echo $html;
?>

Replace google.com in preg_replace with your domain and it should work.

Demo: https://regex101.com/r/kIxMYf/1

EDIT: Just a note that preg_replace probably won't be what you're looking for. After checking that code with multiple instances it doesn't replace all matches, only the last instance. As far as the logic for the expression goes, it works for multiple instances. Demos on RegExr and RegEx101.

SeaWorld
  • 352
  • 3
  • 11
  • how to put original link such as www.google.com in to base64_encode() i tried base64_encode('\\2\\3') but it not working – thanh Jul 20 '19 at 03:38
  • You can do that by using the function `preg_replace_callback`. [PHP Docs](https://www.php.net/manual/en/function.preg-replace-callback.php) is where you can find out a bit more about it. I did also find a good example for you on the topic [here](https://stackoverflow.com/questions/29340600/php-how-to-do-base64encode-while-doing-preg-replace). Just be sure to use your own expression. – SeaWorld Jul 21 '19 at 02:32