Created
May 31, 2011 20:48
-
-
Save honzajavorek/1001255 to your computer and use it in GitHub Desktop.
Find and replace text URLs by HTML clickable links.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Finds and replaces text URLs by HTML clickable links. | |
* | |
* @author Honza Javorek http://www.javorek.net/ | |
* @copyright Copyright (c) 2008 Jan Javorek | |
* @license New BSD License | |
*/ | |
class HtmlLinks { | |
/** | |
* Max length of link. | |
* | |
* @var int | |
*/ | |
public $limit = 30; | |
/** | |
* Characters trimmed from the right end of link. | |
* | |
* @var array | |
*/ | |
public $marks = array(',', '.', '!', '?', '"', '\'', ';', ':', '&'); | |
/** | |
* Supported protocols. | |
* | |
* @var array | |
*/ | |
public $protocols = array('http://', 'https://', 'ftp://'); | |
public function __construct() { | |
} | |
/** | |
* Replaces regular expression matches by a clickable link. | |
* | |
* @param array $matches | |
* @return string | |
*/ | |
private function replaceLink(array $matches) { | |
$match = $matches[0]; | |
$protocol = $matches[2]; | |
$mark = substr($match, -1, 1); | |
// marks at the end | |
if (in_array($mark, $this->marks)) { | |
$match = substr($match, 0, -1); | |
} else { | |
$mark = ''; | |
} | |
// length | |
$len = strlen($match); | |
// http at the beginning | |
$http = ''; | |
if (!in_array($protocol, $this->protocols)) { | |
$http = 'http://'; | |
} | |
// length handling and creating the link | |
if ($len > $this->limit) { | |
return "<a href=\"$http$match\">" . substr($match, 0, $this->limit) . "…</a>$mark"; | |
} else { | |
return "<a href=\"$http$match\">$match</a>$mark"; | |
} | |
} | |
/** | |
* Replaces text URLs by HTML clickable links in given string. | |
* | |
* @param string $s | |
* @return string | |
*/ | |
public function process($s) { | |
return preg_replace_callback( | |
'~(?<![=\\"\\\'\\/])((([a-zA-Z]+:\\/\\/)|(www\\.))[^\\s]+)~i', | |
array($this, 'replaceLink'), // see http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback | |
$s | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment