Home  >  Article  >  Backend Development  >  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?

DDD
DDDOriginal
2024-10-26 12:22:29577browse

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:

<code class="php">$string = preg_replace(
  "~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
  "<a href=\"\0\">\0</a>",
  $string
);</code>

Explanation:

Example:

<code class="php">$input = "Look on http://www.google.com";
$output = preg_replace(
  "~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~",
  "<a href=\"\0\">\0</a>",
  $input
);

echo $output; // Output: "Look on <a href=\"http://www.google.com\">http://www.google.com</a>"</code>

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

The above is the detailed content of How can I turn plain URLs in a string into clickable hyperlinks with PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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