簡體   English   中英

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

[英]php 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);

這就是我到目前為止所得到的,如果字符串中只有 1 個 url ,則鏈接工作和縮短工作也是如此,但是如果有 2 個或更多,它們最終都相同。

如果有 2 個或更多,它們的結果都是一樣的

注意: is.gd不允許在帖子中發布,所以我以為我發布了一個此處不允許的短鏈接,所以我不得不將其更改為isnot.gd

您的變量$link不是數組,因此它只需要$link的最后分配值。 您可以用str_replace替換preg_replace並通過匹配和鏈接傳遞 arrays。

您還可以使用preg_replace_callback()並且可以將 $matches 直接傳遞給 function 將替換為鏈接。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM