简体   繁体   中英

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.

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.

如果有 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 .

Your variable $link is not array so it takes only last assigned value of $link . You can replace preg_replace with str_replace and pass arrays with matches and links.

You can also use preg_replace_callback() and you can pass $matches directly to function which will replace with link. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM