Поворот простых текстовых URL-адресов в активные ссылки с использованием PHP

Я новичок. Мне было интересно, как это сделать, потому что я всегда хотел пошутить с моим другом. Не могли бы вы ответить? Благодаря!

Related of "Поворот простых текстовых URL-адресов в активные ссылки с использованием PHP"

Вы можете задаться вопросом, как это работает. Я попытаюсь объяснить, как это должно быть сделано различными способами. Сначала мы начнем с того, как работает регулярное выражение и как он используется.


Regex – регулярное выражение

При вычислении регулярное выражение (сокращенное регулярное выражение или регулярное выражение) представляет собой последовательность символов, которая формирует шаблон поиска, в основном для использования в сопоставлении с строками или сопоставления строк, т. Е. Операции поиска и замены.

Основной синтаксис

Чтобы использовать регулярные выражения, вам нужно изучить синтаксис. Этот синтаксис состоит из серии букв, цифр, точек, дефиса и специальных знаков, которые мы можем объединить вместе, используя разные круглые скобки.

 ^ The circumflex symbol matches the beginning of the input string or line, although in some cases it can be omitted $ Same as with the circumflex symbol, the dollar sign matches the end of the input string or line . The period matches any single character ? It will match the preceding pattern zero or one times + It will match the preceding pattern one or more times * It will match the preceding pattern zero or more times | Boolean OR - Used when describing a range of elements () Groups pattern elements together [] Matches any single character between the square brackets {min, max} Used to match exact character counts, where min and max are integers \d Matches any single digit \D Matches any single non digit caharcter \w Matches any alpha numeric character including underscore (_) \W Matches any non alpha numeric character excluding the underscore character \s Matches any single whitespace character 

Кронштейны

Скобки [] имеют особое значение при использовании в контексте регулярных выражений. Они используются для поиска диапазона символов.

 [0-9] Matches any decimal digit from 0 through 9. [az] Matches any character from lowercase a through lowercase z. [AZ] Matches any character from uppercase A through uppercase Z. [aZ] Matches any character from lowercase a through uppercase Z. 

Примеры

Давайте посмотрим, как правильно использовать операторы. Мы сделаем это с примером слова hello .

 /hello/ Matches the word hello /^hello/ Matches hello at the start of a string. Possible matches are hello or helloworld, but not worldhello /hello$/ Matches hello at the end of a string or line. /he.o/ Matches any character between he and o. Possible matches are helo or heyo, but not hello /he?llo/ Matches either hllo or hello /hello+/ Matches hello one or more times. Eg matches hello or hellohello /he*llo/ Matches llo, hello or hehello, but not hellooo /hello|world/ Matches either hello or world /(AZ)/ Using the hyphen character to denote a range, matches every uppercase character from A to ZEg A, B, C… /[abc]/ Matches any single character a, b or c /abc{1}/ Matches precisely one c character after the characters ab. Eg matches abc, but not abcc /abc{1,}/ Matches one or more c character after the characters ab. Eg matches abc or abcc /abc{2,4}/ Matches between two and four c character after the characters ab. Eg matches abcc, abccc or abcccc, but not abc 

Самый распространенный

 [^a-zA-Z] Matches any string not containing any of the characters ranging from a through z and A through Z. pp Matches any string containing p, followed by any character, in turn followed by another p. ^.{2}$ Matches any string containing exactly two characters. <b>(.*)</b> Matches any string enclosed within <b> and </b>. p(hp)* Matches any string containing ap followed by zero or more instances of the sequence hp. 

Regex соответствует URL-адресу

Сначала давайте посмотрим, как создается URL-адрес. У нас есть только несколько вариантов:

  • http://example.com/
  • https://example.com/
  • ftp://example.com/
  • www.example.com
  • user@example.com
  • 127.0.0.1
  • http://example.com:8080/

http:// , https:// , ftp , www , mail , ip и port .

Метод 1 (1/10 баллов)

 // Only mails $match = preg_match('/[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+/', $string, $array); 

Метод 2 (5/10 баллов)

 // Without ports, www-s, ip-s and mails $text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\">\\0</a>", $text); 

Метод 3 (10/10 баллов)

 /* Proposed by: * Søren Løvborg * http://stackoverflow.com/users/136796/soren-lovborg */ $rexProtocol = '(https?://)?'; $rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})'; $rexPort = '(:[0-9]{1,5})?'; $rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?'; $rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?'; $rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?'; function callback($match) { // Prepend http:// if no protocol specified $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}"; return '<a href="' . $completeUrl . '">' . $match[2] . $match[3] . $match[4] . '</a>'; } $text = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&", 'callback', htmlspecialchars($text)); . /* Proposed by: * Søren Løvborg * http://stackoverflow.com/users/136796/soren-lovborg */ $rexProtocol = '(https?://)?'; $rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})'; $rexPort = '(:[0-9]{1,5})?'; $rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?'; $rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?'; $rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?'; function callback($match) { // Prepend http:// if no protocol specified $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}"; return '<a href="' . $completeUrl . '">' . $match[2] . $match[3] . $match[4] . '</a>'; } $text = preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&", 'callback', htmlspecialchars($text)); 

Вы можете написать свои собственные идеи для моего ответа.


Я пишу…