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

DDD
Release: 2024-10-26 12:22:29
Original
576 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!