Alternate Code for _expandLinks relative URLs

Ryan
2010-12-10
2013-05-30
  • Ryan
    Ryan
    2010-12-10

    I had issues with relative paths using the current _expandLinks function.

    I found an alternate implementation here that seems to work better (at least for me)
    http://www.php-faq.de/q-regexp-links-absolut.html

    The following is a modified version to replace _expandLinks in Snoopy

    function _expandlinks ($relatives, $absolute)
    {
    $links = array();
    foreach($relatives as $relative)
    {
    if (preg_match(',^(https?://|ftp://|mailto:|news:),i', $relative))
    {
    $links = $relative;
    }
    else
    {
    $url = parse_url($absolute);
    if ($url{strlen($url) - 1} == '/')
    $dir = substr($url, 0, strlen($url) - 1);
    else
    $dir = dirname($url);

    if ($relative{0} == '/') {
    $relative = substr($relative, 1);
    $dir = '';
    }

    elseif (substr($relative, 0, 2) == './')
    $relative = substr($relative, 2);

    else while (substr($relative, 0, 3) == '../') {
    $relative = substr($relative, 3);
    $dir = substr($dir, 0, strrpos($dir, '/'));
    }
    $links = sprintf('%s://%s%s/%s', $url, $url, $dir, $relative);
    }
    }
    return $links;
    }