Home >Backend Development >PHP Tutorial >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()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))'; $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 < 0) { $text = substr($text, 0, $last) . "&hellip;"; } return sprintf(\'<a rel="nofollow" href="%s">%s</a>\', $url, $text); '); return preg_replace_callback($pattern, $callback, $text); }</code>
Breaking Down the Regex Pattern:
The regular expression pattern initializes a greedy search (?i) and looks for the following segments:
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/…
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.
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!