【问题标题】:php shorten all urls with is.gd api in a string and linkify themphp 用 is.gd api 缩短字符串中的所有 url 并将它们链接起来
【发布时间】:2020-05-30 01:15:33
【问题描述】:

正如标题所说,我正在尝试使用 is.gd api 在字符串中缩短 all 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

【问题讨论】:

    标签: php json api foreach preg-match-all


    【解决方案1】:

    您的变量 $link 不是数组,因此它只需要最后分配的值 $link。您可以将 preg_replace 替换为 str_replace 并传递带有匹配项和链接的数组。

    您也可以使用preg_replace_callback() 并且可以将$matches 直接传递给将替换为链接的函数。 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2011-04-28
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多