Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Linkify a URL With PHP (Version 1)

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
  $lengthurl = strlen($url);
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
  $url = preg_replace( "|[^a-z0-9-~+_.?#=!&;,/:%@$*'()x80-xff]|i", '', $url );
31
  $url = str_replace( array( "%0d", "%0a" ), '', $url );
32
  $url = str_replace( ";//", "://", $url );
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
  $url = preg_replace("|&([^#])(?![a-z]{2,8};)|", "&$1", $url);
39
  $url = str_replace("'", "&#039;", $url);
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
  $text = preg_replace( '#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $text );
49
  $text = trim($text);
50
 
51
 return $text;
52
}

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.

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

NOPE