конвертировать обычные текстовые URL-адреса в гиперссылки HTML в PHP

Есть ли способ конвертировать обычные текстовые URL-адреса в HTML-гиперссылки в PHP? Мне нужно преобразовать URL-адреса следующего типа:

http://example.com
http://example.org
http://example.gov/
http://example.com?q=sometext&opt=thisandthat
http://example.com#path
http://example.com?q=querypath#path
http://example.com/somepath/index.html

https://example.com/
https://example.org/
https://example.gov/
https://example.com?q=sometext&opt=thisandthat
https://example.com#path
https://example.com?q=querypath#path
https://example.com/somepath/index.html

http://www.example.com/
http://www.example.org/
http://www.example.gov/
http://www.example.com?q=sometext&opt=thisandthat
http://www.example.com#path
http://www.example.com?q=querypath#path
http://www.example.com/somepath/index.html

https://www.example.com/
https://www.example.org/
https://www.example.gov/
https://www.example.com?q=sometext&opt=thisandthat
https://www.example.com#path
https://www.example.com?q=querypath#path
https://www.example.com/somepath/index.html

www.example.com/
www.example.org/
www.example.gov/
www.example.com?q=sometext&opt=thisandthat
www.example.com/#path
www.example.com?q=querypath#path
www.example.com/somepath/index.html

example.com/
example.org/
example.gov/
example.com?q=sometext&opt=thisandthat
example.com/#path
example.com?q=querypath#path
example.com/somepath/index.html

person Amit    schedule 10.08.2010    source источник
comment
Это исходит из внешнего файла, который вы хотите проанализировать с помощью php?   -  person Sarfraz    schedule 10.08.2010
comment
Что вы хотите, чтобы ссылки читались? Эти ссылки в файле или массиве или что-то еще?   -  person Peter Ajtai    schedule 10.08.2010
comment
Я думаю, вы ищете способ найти такие URL-адреса в тексте, преобразовать их в полные URL-адреса и заменить их HTML-ссылками, верно?   -  person Gumbo    schedule 10.08.2010
comment
Ссылки будут исходить от пользовательского ввода. Я предоставляю текстовое поле для ввода комментариев на моем сайте. Любой URL-адрес в комментарии необходимо преобразовать в ссылку.   -  person Amit    schedule 11.08.2010


Ответы (7)


Как насчет того, чтобы запустить их через регулярное выражение, подобное следующему, используемому для повторной активации ссылок Twitter:

http://www.burnmind.com/howto/how-to-convert-twitter-mentions-and-urls-to-active-links-using-regular-expressions-in-php

person bulkhead    schedule 15.04.2011

Если вам просто нужно преобразовать один URL-адрес, это довольно просто:

function makeLink($url)
{
    return '<a href="' . htmlspecialchars($url) . '">' . htmlspecialchars($url) . '</a>';
}

Для URL-адресов, появляющихся в большем текстовом блоке, например. комментарии пользователей, см. этот вопрос:

person Søren Løvborg    schedule 27.05.2011
comment
Для дополнительных очков вы должны использовать намерение, раскрывающее локальную переменную, а не вызывать htmlspecialcharacters() дважды :) - person Frank Shearar; 28.05.2011
comment
Это дублированный код, да, но я думаю, что htmlspecialchars($url) раскрывает намерение лучше, чем любое имя переменной. :-) - person Søren Løvborg; 29.05.2011

Попробуйте эту функцию. это сделает ссылку, если текст начинается с http или www. example.com не будет работать.

function linkable($text = ''){
    $text = preg_replace("/\s+/", ' ', str_replace(array("\r\n", "\r", "\n"), ' ', $text));
    $data = '';
    foreach( explode(' ', $text) as $str){
        if (preg_match('#^http?#i', trim($str)) || preg_match('#^www.?#i', trim($str))) {
            $data .= '<a href="'.$str.'">'.$str.'</a> ';
        } else {`enter code here`
            $data .= $str .' ';
        }
    }
    return trim($data);
}
person Shanto    schedule 04.06.2011

Э-э, обернуть их тегом привязки?

function linkify($url) {
  return '<a href="' . $url . '">' . $url . '</a>';
}
person Frank Shearar    schedule 10.08.2010
comment
Этот код не работает, так как он не выполняет HTML-экранирование URL-адреса. Самое главное, URL-адреса, содержащие амперсанды, приведут к недопустимому HTML-коду. - person Søren Løvborg; 27.05.2011
comment
Он не делает целую кучу вещей. Я имел в виду не что иное, как самый маленький пример, демонстрирующий концепцию. - person Frank Shearar; 28.05.2011

Это то, что я использую, чтобы делать то же самое на небольшом форуме, который я сделал. Обычно я просматриваю весь комментарий как echo makeLinks($forumpost['comment']);

function makeLinks($str) {    
    return preg_replace('/(https?):\/\/([A-Za-z0-9\._\-\/\?=&;%,]+)/i', '<a href="$1://$2" target="_blank">$1://$2</a>', $str);
}
person cOle2    schedule 27.05.2011

Вот как я это сделал (с включенными тестовыми примерами):

/**
 * @see Inspired by https://css-tricks.com/snippets/php/find-urls-in-text-make-links/ and Example 1 of http://php.net/manual/en/function.preg-replace-callback.php
 * 
 * @param string $text
 * @return string
 */
public static function getTextWithLinksEnabled($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, $text);
}

Тесты:

public function testGetTextWithLinksEnabled() {
    $this->assertEquals('[email protected]', StrT::getTextWithLinksEnabled('[email protected]'));//no links
    $this->assertEquals('just plain text', StrT::getTextWithLinksEnabled('just plain text'));//no links
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here'));//one link
    $this->assertEquals("here is a link <a href='https://stackoverflow.com/'>https://stackoverflow.com/</a> right here and another: <a href='https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'>https://css-tricks.com/snippets/php/find-urls-in-text-make-links/</a>", StrT::getTextWithLinksEnabled('here is a link https://stackoverflow.com/ right here and another: https://css-tricks.com/snippets/php/find-urls-in-text-make-links/'));//2 links
}
person Ryan    schedule 11.02.2019

В случае, если конечный пользователь не включает «http://» или «https://» (в моем случае копирование ссылки в форму). На основе кода Райана выше меня:

function makeLink($text) {
    $regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
    return preg_replace_callback($regex, function ($matches) {
        $fullMatch = $matches[0];
        // $fullMatch = startsWith($fullMatch, 'http') ? $fullMatch : 'http://'.$fullMatch;
        return "<a href='" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, substr( $text, 0, strlen( 'http' ) ) === 'http' ? $text : 'http://'.$text);
}
person dev-jeff    schedule 12.08.2020