gpt4 book ai didi

php - 如何使用 php 将文本区域中的链接转换为链接元素?

转载 作者:可可西里 更新时间:2023-10-31 22:58:49 25 4
gpt4 key购买 nike

我正在创建一个脚本,它包含一个发布脚本,但我希望用户直接从其他任何地方复制一个链接,当他们发布它时,链接文本应该自动将链接转换为链接元素(<a>)。

例如:

Ask this on http://stackoverflow.com now

成为

Ask this on <a href="http://stackoverflow.com">http://stackoverflow.com</a> now

我试过 str_replace()功能,但这不是解决方案。

谁能告诉我解决办法?

最佳答案

为此有多种解决方案,其中大部分都写得不好且不完整。在这种情况下,我建议使用其中一个大型框架的现有解决方案,无需重新发明轮子。

例如,this article on Zenverse描述方式WordPress处理这个。

让我在这里添加代码片段以供进一步引用:

function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];

if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
}

function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;

if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
}

function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}

function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);

// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;
}

链接文章中所写的示例用法:

$string = 'I have some texts here and also links such as http://www.youtube.com , www.haha.com and lol@example.com. They are ready to be replaced.';

echo make_clickable($string);

关于php - 如何使用 php 将文本区域中的链接转换为链接元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6204590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com