This is the first of a few functions that'll linkify text with PHP. It's based on WordPress' make_clickable() function. If you would like to shorten a URL in addition to creating an active link, modify the beliefmedia_create_short() function as required. For truncating purposes, clients will likely want to use our own suite of tools.
1
<?php
2
/*
3
Linkify a URL With PHP (Version 1)
4
http://www.beliefmedia.com/code/php-snippets/linkify-url-php
5
*/
6
7
8
function beliefmedia_linkify($matches, $short = false) {
9
$url = $matches[2];
10
$url = beliefmedia_clean_url($url);
11
if (empty($url)) return $matches[0];
12
13
/* Truncate URL? */
14
if ($short !== false) $url = beliefmedia_create_short($url);
15
16
return "{$matches[1]}<a href='{$url}' target='_blank' rel="noopener noreferrer">{$url}</a>";
17
}
18
19
20
function beliefmedia_create_short($url, $length = '20') {
21
22
23
if ($lengthurl > $length) $url = file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
24
25
return $url;
26
}
27
28
29
function beliefmedia_clean_url($url) {
30
31
if ($url == '') return $url;
32
33
34
35
36
37
/* If the URL doesn't appear to contain a scheme, presume http:// */
38
if (strpos($url, ':') === false && substr( $url, 0, 1 ) != '/' && !preg_match( "|^[a-z0-9-]+?.php|i", $url ) ) $url = "http://{$url}";
39
40
/* Replace ampersans and single quotes */
41
42
43
44
return $url;
45
}
46
47
48
function beliefmedia_transform($text) {
49
50
$text = " {$text}";
51
$text = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is', 'beliefmedia_linkify', $text);
52
53
54
55
return $text;
56
}
Usage is as follows:
1
<?php
2
$text = "This is the first URL: http://www.beliefmedia.com/, and another: http://www.flight.org";
3
echo beliefmedia_transform($text);
Returns the following:
This is the first URL: http://www.beliefmedia.com/, and another: http://www.flight.org
Additional functions that serve a similar purpose are forthcoming.