Home >Backend Development >PHP Tutorial >How to Mimic Stack Overflow\'s Auto-Link Behavior in PHP?
Mimicking Stack Overflow's Auto-Link Behavior in PHP
Many Stack Overflow users have expressed their admiration for the automatic linking functionality of the platform. This article explores how to replicate such behavior in PHP, enabling you to transform URLs into visually appealing links within your own text.
The Auto-Link Regex
The following PHP function utilizes a regular expression pattern from Daring Fireball to identify URLs in text:
<code class="php">function auto_link_text($text) { $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`!()\[\]{};:\'"",<>?«»“”‘’]))'; ... }</code>
Formatting the Links
Once a URL is identified, the function parses it to extract the host and path. This information is then used to create the link text, which is displayed to the user:
<code class="php">... $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH); $text = preg_replace("/^www./", "", $text); $last = -(strlen(strrchr($text, "/"))) + 1; ...</code>
Usage Example
To use the function, simply pass your text to it as an argument:
<code class="php">$text = "..."; $linked_text = auto_link_text($text);</code>
Output
The function will return the input text with URLs converted into HTML links:
Input: This is my text. Check This out http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior Output: This is my text. Check This out <a href="http://www.stackoverflow.com/questions/1925455/how-to-mimic-stackoverflow-auto-link-behavior">stackoverflow.com/questions/1925455/...</a>
The above is the detailed content of How to Mimic Stack Overflow\'s Auto-Link Behavior in PHP?. For more information, please follow other related articles on the PHP Chinese website!