$val) { $attr = ' ' . $key . '="' . htmlentities($val) . '"'; } $links = array(); // Extract existing links and tags $value = preg_replace_callback('~(.*?|<.*?>)~i', function ($match) use (&$links) { return '<' . array_push($links, $match[1]) . '>'; }, $value); // Extract text links for each protocol foreach ((array)$protocols as $protocol) { switch ($protocol) { case 'http': case 'https': $value = preg_replace_callback($mode != 'all' ? '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?' . $link . '') . '>'; }, $value); break; case 'mail': $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?' . $match[1] . '') . '>'; }, $value); break; case 'twitter': $value = preg_replace_callback('~(?' . $match[0] . '') . '>'; }, $value); break; default: $value = preg_replace_callback($mode != 'all' ? '~' . preg_quote($protocol, '~') . '://([^\s<]+?)(?' . $match[1] . '') . '>'; }, $value); break; } } // Insert all link return preg_replace_callback('/<(\d+)>/', function ($match) use (&$links) { return $links[$match[1] - 1]; }, $value); } // Example: $content = 'You can use this function for linking text such as http://amazon.com or www.bn.com, but it also preserves embedded links and other HTML tags.'; echo linkify($content);