"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I turn plain URLs in a string into clickable hyperlinks with PHP?

How can I turn plain URLs in a string into clickable hyperlinks with PHP?

Published on 2024-12-21
Browse:633

How can I turn plain URLs in a string into clickable hyperlinks with PHP?

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).

Latest tutorial More>

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