Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8332681
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T02:47:36+00:00 2026-06-09T02:47:36+00:00

I’ve found many PHP script that convert urls in text to clickable links. But

  • 0

I’ve found many PHP script that convert urls in text to clickable links. But most of them don’t work and some make big bugs. Some of them convert links that are already clickable. Others don’t work and third makes parts from the text links.
I need a script that will detect only links, not the text and will not convert the already clickable links because it’s going on very ugly.

I found this code which seems the best from those I’ve tested. But it has some bugs.
This code converts clickable links. Like this:

Original:

<a href="http://www.netload.in/dateiySgPP2b14W/1409423417ExpFut.pdf.htm" target="_blank">http://www.netload.in/dateiySgPP2b14W/1409...7ExpFut.pdf.htm</a>

Converted:

http://www.netload.in/dateiySgPP2b14W/1409423417ExpFut.pdf.htm" target="_blank">http://www.netload.in/dateiySgPP2b14W/1409...7ExpFut.pdf.htm 

Here is the code:

function parse_urls($text, $maxurl_len = 35, $target = '_self') // Make URLs Clickable
{
    if (preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si', $text, $urls))
    {
        $offset1 = ceil(0.65 * $maxurl_len) - 2;

        $offset2 = ceil(0.30 * $maxurl_len) - 1;

        foreach (array_unique($urls[1]) AS $url)
        {
            if ($maxurl_len AND strlen($url) > $maxurl_len)
            {
                $urltext = substr($url, 0, $offset1) . '...' . substr($url, -$offset2);
            }
            else
            {
                $urltext = $url;
            }

            $text = str_replace($url, '<a href="'. $url .'" target="'. $target .'" title="'. $url .'">'. $urltext .'</a>', $text);
        }
    }

    return $text;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T02:47:38+00:00Added an answer on June 9, 2026 at 2:47 am

    I just threw this together.

    <?php
    function replaceUrlsWithLinks($text){
        $dom = new DOMDocument;
        $dom->loadXML($text);
        $xpath = new DOMXpath($dom);
        $query = $xpath->query('//text()[not(ancestor-or-self::a)]');
        foreach($query as $item){
            $content = $item->textContent;
            if(preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si',$content,$matches,PREG_SET_ORDER | PREG_OFFSET_CAPTURE)){
                foreach($matches as $match){
                    $newA = $dom->createElement('a',$match[0][0]);
                    $newA->setAttribute('href',$match[0][0]);
                    $newA->setAttribute('target','_blank');
                    $a = $item->splitText($match[0][1]);
                    $b = $a->splitText(strlen($match[0][0]));
                    $a->parentNode->replaceChild($newA,$a);
                }
            }
        }
        return $dom->saveHtml();
    }
    // The HTML to process ...
    $html = <<<HTML
    <block>
    <a href="http://google.com">http://google.com</a>
    <b>Stuff http://google.com</b>
    asdf http://google.com ffaa 
    </block>
    HTML;
    // Process the HTML and echo it out.
    echo replaceUrlsWithLinks($html);
    ?>
    

    The output would be:

    <block>
    <a href="http://google.com">http://google.com</a>
    <b>Stuff <a href="http://google.com" target="_blank">http://google.com</a></b>
    asdf <a href="http://google.com" target="_blank">http://google.com</a> ffaa 
    </block>
    

    You shouldn’t use regular expressions to manipulate HTML.

    Hope this helps.

    Kyle

    — Edit —

    The previous code is more efficient, but if you plan to have two URLs in the same parent node, the code will break because the DOM tree is changed. To fix this, you can use this more intensive code:

    <?php
    function replaceUrlsWithLinks($text){
        $dom = new DOMDocument;
        $dom->loadXML($text);
        $xpath = new DOMXpath($dom);
        while(true){
            $shouldBreak = false;
            $query = $xpath->query('//text()[not(ancestor-or-self::a)]');
            foreach($query as $item){
                $shouldBreak = false;
                $content = $item->textContent;
                if(preg_match_all('/((ht|f)tps?:\/\/([\w\.]+\.)?[\w-]+(\.[a-zA-Z]{2,4})?[^\s\r\n\(\)"\'<>\,\!]+)/si',$content,$matches,PREG_SET_ORDER | PREG_OFFSET_CAPTURE)){
                    foreach($matches as $match){
                        $newA = $dom->createElement('a',$match[0][0]);
                        $newA->setAttribute('href',$match[0][0]);
                        $newA->setAttribute('target','_blank');
                        $a = $item->splitText($match[0][1]);
                        $b = $a->splitText(strlen($match[0][0]));
                        $a->parentNode->replaceChild($newA,$a);
                        $shouldBreak = true;
                        break;
                    }
                }
                if($shouldBreak == true)break;
            }
            if($shouldBreak == true){
                continue;
            }
            else {
                break;
            }
        }
        return $dom->saveHtml();
    }
    
    $html = <<<HTML
    <block>
    <a href="http://google.com">http://google.com</a>
    <b>Stuff http://google.com</b>
    asdf http://google.com ffaa  http://google.com
    </block>
    HTML;
    
    echo replaceUrlsWithLinks($html);
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to count how many characters a certain string has in PHP, but
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.