亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

php 在字符串中使用 is.gd api 縮短所有 url 并將它們鏈接起來

php 在字符串中使用 is.gd api 縮短所有 url 并將它們鏈接起來

PHP
慕神8447489 2023-04-21 16:51:40
正如標題所說,我正在嘗試用字符串中的 is.gd api縮短所有url 并將它們鏈接起來。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);這是我到目前為止所得到的,鏈接有效,如果字符串中只有 1 個 url,則縮短也是如此,但是如果有 2 個或更多,它們最終都會相同。注意:在帖子中不允許is.gd,所以我以為我發布了一個在這里不允許的短鏈接,所以我不得不將它更改為isnot.gd。
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

您的變量$link不是數組,因此它只需要最后分配的值$link.?您可以preg_replacestr_replace匹配項和鏈接替換并傳遞數組。

您也可以使用preg_replace_callback()并且可以將 $matches 直接傳遞給將替換為鏈接的函數。

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);

}


查看完整回答
反對 回復 2023-04-21
  • 1 回答
  • 0 關注
  • 157 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號