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
function beliefmedia_linkify($matches, $short = false) {
8
$url = $matches[2];
9
$url = beliefmedia_clean_url($url);
10
if (empty($url)) return $matches[0];
11
12
/* Truncate URL? */
13
if ($short !== false) $url = beliefmedia_create_short($url);
14
15
return "{$matches[1]}<a href='{$url}' target='_blank' rel="noopener noreferrer">{$url}</a>";
16
}
17
18
function beliefmedia_create_short($url, $length = '20') {
19
20
21
if ($lengthurl > $length) $url = file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
22
23
return $url;
24
}
25
26
function beliefmedia_clean_url($url) {
27
28
if ($url == '') return $url;
29
30
31
32
33
34
/* If the URL doesn't appear to contain a scheme, presume http:// */
35
if (strpos($url, ':') === false && substr( $url, 0, 1 ) != '/' && !preg_match( "|^[a-z0-9-]+?.php|i", $url ) ) $url = "http://{$url}";
36
37
/* Replace ampersans and single quotes */
38
39
40
41
return $url;
42
}
43
44
function beliefmedia_transform($text) {
45
46
$text = " {$text}";
47
$text = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is', 'beliefmedia_linkify', $text);
48
49
50
51
return $text;
52
}
Usage is as follows:
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.