在 PHP 中将纯文本 URL 转换为 HTML 超链接

发布于 2024-09-13 08:55:46 字数 1341 浏览 6 评论 0原文

有没有办法在 PHP 中将纯文本 URL 转换为 HTML 超链接?我需要转换以下类型的 URL:

http://example.com
http://example.org
http://example.gov/
http://example.com?q=sometext&opt=thisandthat
http://example.com#path
http://example.com?q=querypath#path
http://example.com/somepath/index.html

https://example.com/
https://example.org/
https://example.gov/
https://example.com?q=sometext&opt=thisandthat
https://example.com#path
https://example.com?q=querypath#path
https://example.com/somepath/index.html

http://www.example.com/
http://www.example.org/
http://www.example.gov/
http://www.example.com?q=sometext&opt=thisandthat
http://www.example.com#path
http://www.example.com?q=querypath#path
http://www.example.com/somepath/index.html

https://www.example.com/
https://www.example.org/
https://www.example.gov/
https://www.example.com?q=sometext&opt=thisandthat
https://www.example.com#path
https://www.example.com?q=querypath#path
https://www.example.com/somepath/index.html

www.example.com/
www.example.org/
www.example.gov/
www.example.com?q=sometext&opt=thisandthat
www.example.com/#path
www.example.com?q=querypath#path
www.example.com/somepath/index.html

example.com/
example.org/
example.gov/
example.com?q=sometext&opt=thisandthat
example.com/#path
example.com?q=querypath#path
example.com/somepath/index.html

Is there anyway to convert plain text URLs to HTML hyperlinks in PHP? I need to convert URLs of following type:

http://example.com
http://example.org
http://example.gov/
http://example.com?q=sometext&opt=thisandthat
http://example.com#path
http://example.com?q=querypath#path
http://example.com/somepath/index.html

https://example.com/
https://example.org/
https://example.gov/
https://example.com?q=sometext&opt=thisandthat
https://example.com#path
https://example.com?q=querypath#path
https://example.com/somepath/index.html

http://www.example.com/
http://www.example.org/
http://www.example.gov/
http://www.example.com?q=sometext&opt=thisandthat
http://www.example.com#path
http://www.example.com?q=querypath#path
http://www.example.com/somepath/index.html

https://www.example.com/
https://www.example.org/
https://www.example.gov/
https://www.example.com?q=sometext&opt=thisandthat
https://www.example.com#path
https://www.example.com?q=querypath#path
https://www.example.com/somepath/index.html

www.example.com/
www.example.org/
www.example.gov/
www.example.com?q=sometext&opt=thisandthat
www.example.com/#path
www.example.com?q=querypath#path
www.example.com/somepath/index.html

example.com/
example.org/
example.gov/
example.com?q=sometext&opt=thisandthat
example.com/#path
example.com?q=querypath#path
example.com/somepath/index.html

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

一抹微笑 2024-09-20 08:55:46

如何通过正则表达式运行它们,如下所示,用于重新激活 Twitter 链接 -

http://www.burnmind.com/howto/how-to-convert-twitter-mentions-and-urls-to-活跃链接使用正则表达式在 php

How about running them through a regular expression like the following used to re-activate Twitter links -

http://www.burnmind.com/howto/how-to-convert-twitter-mentions-and-urls-to-active-links-using-regular-expressions-in-php

寂寞笑我太脆弱 2024-09-20 08:55:46

如果您只需要转换单个 URL,则非常简单:

function makeLink($url)
{
    return '<a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a>';
}

对于出现在较大文本块中的 URL,例如用户评论,请参阅此问题:

If you just need to convert a single URL, it's quite easy:

function makeLink($url)
{
    return '<a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a>';
}

For URLs appearing in a larger text block, e.g. user comments, see this question:

缺⑴份安定 2024-09-20 08:55:46

试试这个功能。如果文本以 http 或 www 开头,这将创建链接。 example.com 将无法工作。

function linkable($text = ''){
    $text = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text));
    $data = '';
    foreach( explode(' ', $text) as $str){
        if (preg_match('#^http?#i', trim($str)) || preg_match('#^www.?#i', trim($str))) {
            $data .= '<a href="'.$str.'">'.$str.'</a> ';
        } else {`enter code here`
            $data .= $str .' ';
        }
    }
    return trim($data);
}

Try this function. this will make link if text start with http or www. example.com will not work.

function linkable($text = ''){
    $text = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text));
    $data = '';
    foreach( explode(' ', $text) as $str){
        if (preg_match('#^http?#i', trim($str)) || preg_match('#^www.?#i', trim($str))) {
            $data .= '<a href="'.$str.'">'.$str.'</a> ';
        } else {`enter code here`
            $data .= $str .' ';
        }
    }
    return trim($data);
}
养猫人 2024-09-20 08:55:46

呃,将它们包裹在锚标签中?

function linkify($url) {
  return '<a href="' . $url . '">' . $url . '</a>';
}

Er, wrap them in an anchor tag?

function linkify($url) {
  return '<a href="' . $url . '">' . $url . '</a>';
}
往昔成烟 2024-09-20 08:55:46

这就是我在我制作的一个小论坛上用来做同样事情的方法。一般来说,我会通过它运行整个评论,例如 echo makeLinks($forumpost['comment']);

function makeLinks($str) {    
    return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%,]+)/i', '<a href="$1://$2" target="_blank">$1://$2</a>', $str);
}

This is what I use to do the same thing on a small forum I made. Generally I run the whole comment through it like echo makeLinks($forumpost['comment']);

function makeLinks($str) {    
    return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%,]+)/i', '<a href="$1://$2" target="_blank">$1://$2</a>', $str);
}
睫毛上残留的泪 2024-09-20 08:55:46

这是我的做法(包括测试用例):

/**
 * @see Inspired by https://css-tricks.com/snippets/php/find-urls-in-text-make-links/ and Example 1 of http://php.net/manual/en/function.preg-replace-callback.php
 * 
 * @param string $text
 * @return string
 */
public static function getTextWithLinksEnabled($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, $text);
}

测试:

public function testGetTextWithLinksEnabled() {
    $this->assertEquals('[email protected]', StrT::getTextWithLinksEnabled('[email protected]'));//no links
    $this->assertEquals('just plain text', StrT::getTextWithLinksEnabled('just plain text'));//no links
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here'));//one link
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here and another: <a href='https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'>https://css-tricks.com/snippets/php/find-urls-in-text-make-links/</a>", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here and another: https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'));//2 links
}

Here is how I did it (with test cases included):

/**
 * @see Inspired by https://css-tricks.com/snippets/php/find-urls-in-text-make-links/ and Example 1 of http://php.net/manual/en/function.preg-replace-callback.php
 * 
 * @param string $text
 * @return string
 */
public static function getTextWithLinksEnabled($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, $text);
}

Tests:

public function testGetTextWithLinksEnabled() {
    $this->assertEquals('[email protected]', StrT::getTextWithLinksEnabled('[email protected]'));//no links
    $this->assertEquals('just plain text', StrT::getTextWithLinksEnabled('just plain text'));//no links
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here'));//one link
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here and another: <a href='https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'>https://css-tricks.com/snippets/php/find-urls-in-text-make-links/</a>", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here and another: https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'));//2 links
}
她如夕阳 2024-09-20 08:55:46

如果最终用户不包含“http://”或“https://”(在我的例子中将链接复制到表单中)。
基于我上面 Ryan 的代码:

function makeLink($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        // $fullMatch = startsWith($fullMatch, 'http') ? $fullMatch : 'http://'.$fullMatch;
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, substr( $text, 0, strlen( 'http' ) ) === 'http' ? $text : 'http://'.$text);
}

In case the end user doesn't include 'http://' or 'https://' (in my case copying a link into a form).
Based on Ryan's code above me:

function makeLink($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        // $fullMatch = startsWith($fullMatch, 'http') ? $fullMatch : 'http://'.$fullMatch;
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, substr( $text, 0, strlen( 'http' ) ) === 'http' ? $text : 'http://'.$text);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文