Home Backend Development PHP Tutorial How Can I Implement Stack Overflow\'s Auto-Link Functionality in PHP?

How Can I Implement Stack Overflow\'s Auto-Link Functionality in PHP?

Nov 04, 2024 am 11:35 AM

How Can I Implement Stack Overflow's Auto-Link Functionality in PHP?

Mimicking Stack Overflow's Auto-Link Feature in PHP

Stack Overflow's auto-link behavior is highly convenient, allowing users to effortlessly link to websites or specific content within a post. This article explores how to implement a similar functionality in PHP, leveraging a regex pattern to identify and convert URLs into HTML links.

To understand the inner workings, let's break down the provided code:

<code class="php">/**
 * Replace links in text with html links
 *
 * @param  string $text
 * @return string
 */
function auto_link_text($text)
{
    // a more readably-formatted version of the pattern is on http://daringfireball.net/2010/07/improved_regex_for_matching_urls
    $pattern = '(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()&lt;&gt;]+|\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\))+(?:\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\)|[^\s`!()\[\]{};:\'".,&lt;&gt;?«»“”‘’]))';

    $callback = create_function('$matches', '
        $url       = array_shift($matches);
        $url_parts = parse_url($url);

        $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
        $text = preg_replace("/^www./", "", $text);

        $last = -(strlen(strrchr($text, "/"))) + 1;
        if ($last &lt; 0) {
            $text = substr($text, 0, $last) . &quot;&amp;amp;hellip;&quot;;
        }

        return sprintf(\'&lt;a rel=&quot;nofollow&quot; href=&quot;%s&quot;&gt;%s&lt;/a&gt;\', $url, $text);
    ');

    return preg_replace_callback($pattern, $callback, $text);
}</code>
Copy after login

Breaking Down the Regex Pattern:

The regular expression pattern initializes a greedy search (?i) and looks for the following segments:

  • Protocol: a-z :
  • Domain: wwwd{0,3}[.]|[a-z0-9.-] .{2,4}
  • Path: /(?:1 |((2 |((3 ))))) (?:((4 |((5 ))))|6))

Custom Callback Function:

The callback function constructs the HTML link markup. It extracts the URL, parses it, removes the leading "www" from the domain, limits the displayed URL text if needed, and finally generates the anchor tag with appropriate attributes.

Sample Input and Output:

To illustrate the function's operation, consider the following input text:

"This is my text. I wonder if you know about asking questions on StackOverflow: Check This out https://www.php.cn/link/6e212075e04d1616b06a5e1398e10053

Also, base_convert php function?
https://www.php.cn/link/63c0d1be32c9c7e2dee3ac21690e490c

https://www.php.cn/link/a995b410d5e76ed56523533b47e3786a"

The output after processing by the auto_link_text() function is:

"This is my text. I wonder if you know about asking questions on StackOverflow: Check This out stackoverflow.com/questions/1925455/…

Also, base_convert php function?
pt.php.net/manual/en/…

pt.php.net/manual/en/…"

By implementing these techniques, developers can effortlessly incorporate Stack Overflow's auto-linking functionality into their PHP applications, enhancing user experience and simplifying content referencing by both writers and readers.


  1. s()<>
  2. s()<>
  3. s()<>
  4. s()<>
  5. s()<>
  6. s`!()[]{};:'".,<>?«»“”‘’

The above is the detailed content of How Can I Implement Stack Overflow\'s Auto-Link Functionality in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

Announcement of 2025 PHP Situation Survey

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

Notifications in Laravel

See all articles