PHP preg_replace URL

To search for urls and convert them into html links you may use preg_replace() in PHP. Though writing regular expression might be not very easy. Here is an example of regular expression which will catch and replace urls which may be:

  • in the beginning of string,
  • in the end of string,
  • configurable prefix/suffix delimiter,
  • with configurable scheme.
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
<?php
 
// configurable delimiters and schemes
$delimiters = '\\s"\\.\',';
$schemes = 'https?|ftps?';
 
$pattern = sprintf('#(^|[%s])((?:%s)://\\S+[^%1$s])([%1$s]?)#i', $delimiters, $schemes);
$replacement = '$1<a href="$2">$2</a>$3';
 
$subjects = array(
    'http://localhost',
    'https://example.com',
    ' ftp://example.com',
    'ftps://example.com ',
    'prefix http://example.com',
    'http://example.com suffix',
    'prefix http://example.com/path suffix',
    'prefix http://example.com/path&var=val suffix',
    'prefix http://example.com/path&var=val, suffix',
    'prefix http://example.com/path&var=val. suffix',
    'prefix "http://example.com/path&var=val" suffix',
    'prefix \'http://example.com/path&var=val\' suffix',
);
 
foreach ($subjects as $subject) {
    var_dump(preg_replace($pattern, $replacement, $subject));
}

One Response

  1. I’ve been searching all over for some script that does this! Thank you :)

Leave a Reply