Linking URLs in Strings with PHP
Linking URLs in strings can be a useful task in PHP for tasks such as generating clickable links in textual content. One common use case is converting a plain string containing URLs into HTML with clickable hyperlinks.
Syntax:
$string = preg_replace(
"~[[:alpha:]] ://[^<>[:space:]] [[:alnum:]/]~",
"<a href=\"\\0\">\\0</a>",
$string
);
Explanation:
Example:
$input = "Look on http://www.google.com";
$output = preg_replace(
"~[[:alpha:]] ://[^<>[:space:]] [[:alnum:]/]~",
"<a href=\"\\0\">\\0</a>",
$input
);
echo $output; // Output: "Look on http://www.google.com"
PHP Versions:
This solution is compatible with both PHP versions prior to 5.3 (using ereg_replace) and PHP 5.3 and later (using preg_replace).
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3