Repository navigation
Expand file tree
/
Copy pathautolinker.php
More file actions
75 lines (68 loc) · 2.22 KB
/
Copy pathautolinker.php
File metadata and controls
75 lines (68 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* AutoLinker class automatically converts inline urls and email address in strings into
* clickable links.
*
* @author Seb Pollard <seb@spolster.co.uk>
* @version 1
*/
class AutoLinker {
/**
* Converts all urls and emails to links.
* @param string $string The text (possibly) containing emails/urls.
* @return string The processed text.
*/
static public function linkAll($string) {
$string = self::linkEmails($string);
return self::linkURLS($string);
}
/**
* Wraps all urls in passed text in a tags.
* @param string $string The text (possibly) containing urls.
* @return string The processed text.
*/
static public function linkURLs($string) {
return preg_replace_callback(
"/
([\s]|^) # word boundary or start of string.
(\()? # (optional) opening parenthesis.
(https?:\/\/)? # (optional) protocol
( # begin domain name
([A-Z0-9]([A-Z0-9\-]{0,61}[A-Z0-9])?\.)+ # One or more subdomains
# (1-63 chars per rfc1035, plus trailing dot)
[A-Z]{2,6} # top-level domain (2-6 chars)
) # end domain name
(\/[A-Z0-9\/\.\-\_\?\=\&\+\%\#]+)? # path
(\))? # (optional) closing parenthesis.
(\s|$) # word boundary or end of string
/ix",
array('AutoLinker', "_linkUrlsCallback"), $string);
}
static private function _linkUrlsCallback($matches) {
if (empty($matches[3])) {
$matches[3] = "http://";
}
if (empty($matches[7])) {
$matches[7] = "";
}
$url = $matches[3] . $matches[4] . $matches[7];
if ($matches[2] == "(" && $matches[8] == ")") { // link in parentheses.
$pre = $matches[1] . $matches[2];
$post = $matches[8] . $matches[9];
}
else {
$pre = $matches[1];
$post = $matches[9];
$url .= $matches[8];
}
return $pre . '<a href="' . $url . '">' . $url . '</a>' . $post;
}
/**
* Wraps all email address in passed text in a tags (mailto:).
* @param string $string The text (possibly) containing email addresses.
* @return string The processed text.
*/
static public function linkEmails($string) {
return preg_replace("/\b([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b/i", "<a href='mailto:\\1'>\\1</a>", $string);
}
}