конвертирайте 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="/bg' . 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="/bg'.$str.'">'.$str.'</a> ';
        } else {`enter code here`
            $data .= $str .' ';
        }
    }
    return trim($data);
}
person Shanto    schedule 04.06.2011

Ъъъ, да ги увиете в котвен етикет?

function linkify($url) {
  return '<a href="/bg' . $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="/bg$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='/bg" . $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='/bg" . $fullMatch . "'>" . $fullMatch . "</a>";
    }, substr( $text, 0, strlen( 'http' ) ) === 'http' ? $text : 'http://'.$text);
}
person dev-jeff    schedule 12.08.2020