在 PHP 字符串中找到一个链接并将其转换为超链接


Find a Link in PHP String and convert it into a Hyperlink?

在 PHP 字符串中找到一个链接并将其转换为超链接,使其变为可单击并在新选项卡中打开。

PHP 代码/字符串:

<?php echo $post_details['description']; ?>

测试链接:

http://www.test.com
使用此库。 它会自动检测字符串

中的链接并使其可单击。 您无需创建链接,只需添加具有链接的字符串即可。 该库将自动检测它。

http://soapbox.github.io/jQuery-linkify/

使用此示例来解决您的问题

<?php
function makeClickableLink($text) {
    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_'+.~#?&//=]+)', '<a href="''1">''1</a>', $text);
    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_'+.~#?&//=]+)', '''1<a href="http://''2">''2</a>', $text);
    $text = eregi_replace('([_'.0-9a-z-]+@([0-9a-z][0-9a-z-]+'.)+[a-z]{2,3})', '<a href="mailto:''1">''1</a>', $text);
    return $text;
}
// Usage 
// Email address example
$text = "you@example.com";
echo makeClickableLink($text);
// URL example
$text = "http://www.example.com";
echo makeClickableLink($text);  
// FTP URL example
$text = "ftp://ftp.example.com";
echo makeClickableLink($text); 
?>