rewrite/mask external link inside article


I want to rewrite/mask all external url in my article and also add nofollow and target="_blank". So that original link to the external site is get encrypted/ masked/ rewritten.

For example:

original link:
rewrite it to:

There is a plugin for joomla which rewrite external link: rewrite plugin.

But I am not using joomla. Please have a look at above plugin, It does exactly what I am looking for.

What I want?

$article = "hello this is example article I want to replace all external link";
$host = substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.' ? substr($_SERVER['HTTP_HOST'], 0) : $_SERVER['HTTP_HOST'];

if (thisIsNotMyWebsite){
    replace external url






You can use DOMDocument to parse and traverse the document.

function rewriteExternal($html) {

        // The url for your redirection script
        $prefix = '';

        // a regular expression to determine if
        // this link is within your site, edit for your
        // domain or other needs
        $is_internal = '/(?:^/|^../)|';

    $dom = new DOMDocument();

    // Parse the HTML into a DOM

    $links = $dom->getElementsByTagName('a');

    foreach ($links as $link) {
            $href = $link->getAttribute('href');
            if (!preg_match($is_internal, $href)) {
                $link->getAttributeNode('href')->value = $prefix . $href;
                $link->setAttributeNode(new DOMAttr('rel', 'nofollow'));
                $link->setAttributeNode(new DOMAttr('target', '_blank'));

    // returns the updated HTML or false if there was an error
    return $dom->saveHTML();

This approach will be much more reliable than using a regular expression based solution since it actually parses the DOM for you instead of relying on a often-fragile regex.


Facebook Comments

Website Comments

  1. Sabina

    I have een browsing online more than 3 hurs today, yet
    I never found any interesting article like
    yours. It is pretty worth enough for me. Personally, iif all web owners and bloggers made good contdnt as you did,
    the net will be much more useful than ever before.|
    I could nott resist commenting. Perfechtly written!|
    I will immediately snatch your rss as I can not in finding your email subscription hyperlink or newsletter service.
    Do you’ve any? Please let me recognise so that I may just subscribe.

    It’s appropriate time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I desife to suggest you few interesting
    things orr suggestions. Maybe you could wrte next articles referring to this article.
    I wish too rwad more things about it!|
    It is appropriate time to make a few plans for the long run and
    it’s time to be happy. I’ve learn this submit and if I may just
    I want to recommend yoou some attention-grabbing things orr advice.
    Maybe you can write next articles referring to this article.
    I want to learn even more things approximately it!|
    I’ve been browsing on-line more than three hours nowadays, but I bby no means found any interesting article like yours.

    It’s lovely worth sufficient for me. In my opinion, iff all
    website owners and bloggbers made good content material as you did,
    the web shall bee a lot more helpful than ever before.|
    Ahaa, its good dialogue coincerning this post at this place at this
    webpage, I have read all that, so at this time me also commenting at this place.|
    I amm sure this article has toouched all the internet users, its really really good piece oof writing
    on building up new website.|
    Wow, this piece of writing is fastidious, my younger sister iis
    analyzing such things, therefore I am going to convey her.|
    bookmarked!!, I love your web site!|
    Way cool! Some very valid points! I appreciate you writing this article plus the rdst of the website is also
    very good.|
    Hi, I do believe this is a great site. I stumbledupon it ;
    ) I am going to come back yet again since i have
    saved as a favorite it. Money and freeddom is the best way to change,
    may you be rich and cntinue to guide others.|
    Woah! I’m really diggig the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s tough too get that “perfect balance” between usability
    and appearance. I must say you’ve done a awesome
    job with this. In addition, the blog loads extremely quick foor
    me on Chrome. Excellent Blog!|
    These are genuinely wonderful ideeas in concerning blogging.
    You have touched some nicfe points here. Any way keep up wrinting.|
    I enjoy what you guys are up too. Such clever workk and coverage!

    Keep up the awesome works guys I’ve included you guys to my blogroll.|
    Howdy! Someone in my Facebook group shared
    this website with us so I came to take a look. I’m
    definitely loving the information. I’m bookmarking and will be
    tweeting this to my followers! Grezt blog and wonderful design.|
    I enjoy what youu guys aree up too. This type of clever work
    and exposure! Keep up the god works guys I’ve incorporated you guys to blogroll.|
    Hey ther would yyou mind stating which blog platfform you’re working with?

    I’m going to start my own blg soon but I’m having a difficult time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your design and style seems different
    then most logs and I’m looking ffor something unique.
    P.S Apologies for being off-topic but I had to ask!|
    Hi there would you mind lettkng me know which webhost you’re working with?
    I’ve loaded your blog in 3 completely different browsers and I
    must say this blog loads a lot quicker theen most. Can you recommend a good hosting providerr at a reasonable price?
    Kudos, I appreciate it!|
    Everyone loves it when ndividuals get together and share opinions.
    Great website, continue the good work!|
    Thank you for the auspicious writeup. It in fact
    was a amusement account it. Look advanced to more added agreeable from you!
    However, how could wwe communicate?|
    Hi there just wanted too give you a quick heads up.
    The words in your article seem to be running off the
    screen inn Chrome. I’m not sure if this is a formatting
    issue or something to do with web browser compatibility butt I figured
    I’d post to let youu know. The layout look great though!
    Hope you get thee issue fixed soon. Cheers|
    This is a topic that iis close to my heart… Best
    wishes! Where are your contact details though?|
    It’s verdy straightforward to find out any topic on web
    as compared to books, as I found this piece of writing at this web page.|
    Does your site have a contact page? I’m having a tough tije locating iit but, I’d
    like to send you an e-mail. I’ve got some creative ideas for your blog you might be interested
    in hearing. Either way, great blog and I look forward to seeing it grow
    over time.|
    Hello! I’ve been following your blog for some
    time now and finally got the courage to go ahead and
    give yoou a shout out from Neww Caney Texas! Just wanted to say keep
    up the fantastic work!|
    Greetings from Idaho! I’m bored to tears
    at work so I decided to browse your website on my iphone during lunch break.
    I love the information you present hefe and can’t wait to take a look when I get home.
    I’m surprised at how fast your blog loaded on myy phone ..
    I’m not even using WIFI, just 3G .. Anyways, good blog!|
    Its like you learn my mind! You seem to grasp so much approximately this,
    like you wroe thhe guide inn it or something. I believe that you
    jut could do with a few % to force the message house a bit, however instead of that, this is magnificent
    blog. A fantastic read. I will certainly be back.|
    I visited multiple websites however the
    auhdio quality for audio songs current att thus web site is actually fabulous.|
    Howdy, i read your blog from time to time and i own a siimilar one and i was just curious if you get a lot of spam feedback?
    If so how do you protect against it, any plugin or anything you can recommend?
    I get so much lately it’s driving me crazy so any support is very mch appreciated.|
    Greetings! Very helpful advice in this particular post! It iss the little hanges
    which wijll make the most significant changes. Thanks a lot for sharing!|
    I absoluytely love your website.. Pleasant colors & theme. Did you create
    thos website yourself? Please reply back as I’m planning to create my own site and want to learn where
    you got this from orr exactly what the theme
    is named. Kudos!|
    Hi there! This post couldn’t be written much better!
    Looking tthrough this article reminds me of my previous roommate!
    He continually kept talking about this. I will forward
    this information to him. Fairly certain he’ll have a good read.
    I appreciate you for sharing!|
    Whoa! This blog looks just ljke my olld one!
    It’s on a entirely different subject but it has pretty much tthe same
    page layout and design. Outstanding choice of colors!|
    There is certainly a lot to learn about this subject.
    I like all of the points you’ve made.|
    You made soke really good points there. I looked on the net for additional infrormation about
    the issue aand found most people will go along with your views on thus wweb site.|
    Hi, I log on to your new stuff regularly. Your story-telling style is awesome, keep doing what you’re doing!|
    I siomply couldn’t depart your web site prior to suggesting that I really lkved the standard information a person provide on your
    guests? Is gohna be again frequently in order to check up on new posts|
    I ned to to thank you for this very good read!!

    I absolutely loved every bit of it. I have you
    saved as a favorite to look at new stuff you post…|
    Hello, just wanted to say, I enjoyed this blog post.It was funny.

    Keep oon posting!|
    Hi there, I enjoy rreading through your article. I wanred
    to write a little comment to support you.|
    Ialwasys spent my half an hour to reead this website’s
    articles orr reviews everyday along with a mug of coffee.|
    I constantly emaled this website post page to alll my friends, because if like to read it next my contacts will too.|
    My coder is treying to convince mme to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve bee using WordPress on various websites for
    about a year and am worried about switching tto another platform.
    I have heard excellent things about
    Is there a wayy I can import all my wordpress posts into
    it? Any ind of help would be greatly appreciated!|
    Howdy! I could have sworn I’ve visited this web site before but after going through some of the articles I realized it’s new to me.
    Anyhow, I’m certainly pleased I discovered it and I’ll be bookmarking it and checking back often!|
    Wonderful article! This is the typee of information that should be
    shared around the net. Disgrace on Google for
    now not positiobing this put up upper! Come on over
    and discuss with my site . Thank you =)|
    Heya i’m for the fijrst time here. I came across this board and I find It really useful & it helped me out much.
    I hope to give something back and help others like you aided me.|
    Hi there, I do believe your wevsite might be having internet browser compatibility issues.
    Whenever I tazke a look at your blog in Safari, it looks fine however, when opening
    in IE, it has some overlapping issues. I simply wanted to provide you
    with a quick heads up! Apart from that, wonderful site!|
    Somebody essentially assist to make severely posts I would state.
    This is thhe first time I frequented your web page and to this point?
    I amazed with the research you made to create this actual publish incredible.
    Great activity!|
    Heya i’m ffor the first time here. I found this board and I in finding It
    truly helpful & it helped me out a lot. I hope to give one thing back and aid
    others ssuch as you helped me.|
    Hi! I simply wish to offer you a huge thumbs
    up foor your great info you have got right here on this
    post. I’ll be coming back to your website for more
    I every time used too read post in new papers but now as I am a user
    oof web thus from now I am using net for articles or reviews, thanks to web.|
    Your method of telling everything in this piece of writing
    is really good, all be able to effortlessly be aware of it, Thanks
    a lot.|
    Hello there, I found your site by the use of Google while looking foor
    a related matter, your site came up, it appears good.
    I have bookmarked it in my google bookmarks.
    Hi there, simply wass aware of your blog through Google, and found that it is truly informative.

    I am gonna be careful for brussels. I will appreciate
    in case you continue this in future. A lot of other folks will probably be
    benefited out off your writing. Cheers!|
    I’m curious to find ouut what blog system you’re woorking with?
    I’m having some minor security problems with my
    latest weebsite and I would like tto find something more
    safe. Do you have anyy suggestions?|
    I am extremely impressed with yourr writing skills and also with thee layout
    on your weblog. Is this a paid theme or did you modify it yourself?
    Anyway keep up the nice quality writing, it is rare to see a nice blog like this one these days.|
    I am extremely impressed together with your writong abilities as neatly
    as with the format for your weblog. Is that this a paid
    topic or did you customize it your self? Either waay stay up the excellent quality
    writing, itt is rare to look a great weblog liike this one today..|
    Hi, Neat post. There is a problem together with your site
    inn internnet explorer, might check this? IE still is the market chief
    aand a huge component to folks will omit your great writing because
    of this problem.|
    I am not sure where you’re getting your
    information, but great topic. I needs to spend some time learning much more or
    understanding more. Thasnks for wonderful information I was looking for this info for my mission.|
    Hello, i think that i saww you visited my site thus i came to “return the favor”.I’m attempting to find things to improve my site!Isuppose
    its ok tto use some of your \

  2. silicone bracelets

    I have been browsing online more than 2 hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did,
    the net will be much more useful than ever before.

  3. rubber bracelets

    Hiya very cool blog!! Man .. Excellent .. Amazing ..

    I’ll bookmark your website and take the feeds also…I am
    happy to search out so many useful information here in the publish, we’d like
    develop more techniques in this regard, thank you
    for sharing.

  4. wristband

    I drop a comment each time I especially enjoy a post on a site or I have
    something to valuable to contribute to the conversation. Usually it’s caused by the sincerness communicated in the post I browsed.

    And after this article rewrite/mask external link inside article – Site Questions
    & Answer. I was actually moved enough to drop a thought :
    -) I actually do have a couple of questions for you if it’s allright.
    Is it simply me or do some of these comments appear like they are
    left by brain dead visitors? 😛 And, if you are posting at other sites, I’d like to keep
    up with you. Would you make a list the complete urls
    of all your public pages like your twitter feed, Facebook page or
    linkedin profile?

  5. fundraiser bracelets

    Thank you so much regarding giving my family an update on this
    issue on your web page. Please know that if
    a brand-new post appears or in the event that any alterations occur to the current article, I would be interested in reading
    more and understanding how to make good using of those strategies
    you talk about. Thanks for your efforts and consideration of people by making this site available.

Post a comment