[英]php shorten all urls with is.gd api in a string and linkify them
As the title says I'm trying to shorten all urls with is.gd api in a string and linkify them.正如标题所说,我正在尝试在字符串中使用 is.gd api 缩短所有网址并将它们链接起来。
function link_isgd($text)
{
$regex = '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)@';
preg_match_all($regex, $text, $matches);
foreach($matches[0] as $longurl)
{
$tiny = file_get_contents('http://isnot.gd/api.php?longurl='.$longurl.'&format=json');
$json = json_decode($tiny, true);
foreach($json as $key => $value)
{
if ($key == 'errorcode')
{
$link = $longurl;
}
else if ($key == 'shorturl')
{
$link = $value;
}
}
}
return preg_replace($regex, '<a href="'.$link.'" target="_blank">'.$link.'</a>', $text);
}
$txt = 'Some text with links https://www.abcdefg.com/123 blah blah blah https://nooodle.com';
echo link_isgd($txt);
This is what I have got so far, linkifying works and so does shortening if only 1 url is in the string, however if theres 2 or more they all end up the same.这就是我到目前为止所得到的,如果字符串中只有 1 个 url ,则链接工作和缩短工作也是如此,但是如果有 2 个或更多,它们最终都相同。
Note: the is.gd
was not allowed in post, SO thought I was posting a short link which is not allowed here, so I had to change it to isnot.gd
.注意: is.gd
不允许在帖子中发布,所以我以为我发布了一个此处不允许的短链接,所以我不得不将其更改为isnot.gd
。
Your variable $link
is not array so it takes only last assigned value of $link
.您的变量$link
不是数组,因此它只需要$link
的最后分配值。 You can replace preg_replace
with str_replace
and pass arrays with matches and links.您可以用str_replace
替换preg_replace
并通过匹配和链接传递 arrays。
You can also use preg_replace_callback()
and you can pass $matches directly to function which will replace with link.您还可以使用preg_replace_callback()
并且可以将 $matches 直接传递给 function 将替换为链接。 https://stackoverflow.com/a/9416265/7082164 https://stackoverflow.com/a/9416265/7082164
function link_isgd($text)
{
$regex = '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-~]*(\?\S+)?)?)?)@';
preg_match_all($regex, $text, $matches);
$links = [];
foreach ($matches[0] as $longurl) {
$tiny = file_get_contents('http://isnot.gd/api.php?longurl=' . $longurl . '&format=json');
$json = json_decode($tiny, true);
foreach ($json as $key => $value) {
if ($key == 'errorcode') {
$links[] = $longurl;
} else if ($key == 'shorturl') {
$links[] = $value;
}
}
}
$links = array_map(function ($el) {
return '<a href="' . $el . '" target="_blank">' . $el . '</a>';
}, $links);
return str_replace($matches[0], $links, $text);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.