- RegEx to convert URLs in text into clickable ones with custom anchor text [closed]
- http://www.website.com/1/
- Click here http://www.website.com/2/ or visit the website: http://www.website.com/3/
- or http://www.website.com/4/
- http://www.website.com/5/
- <a href="http://www.website.com/1/">http://www.website.com/1/</a>
- Click <a href="http://www.website.com/2/">here</a> or visit the website: <a href="http://www.website.com/3/">http://www.website.com/3/</a>
- or <a href="http://www.website.com/4/">http://www.website.com/4/</a>
- <a href="http://www.website.com/5/">http://www.website.com/5/</a>
- preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="\2" target="_blank">\2</a>", $ret);
- // ^---- I've tried adding "|here "
- // But I cannot get the order of \1 and \2 right
- (?:(here)s*|b)(w+?://[w#$%&~/.-;:=,?@[]+]*)
- <a href="$2">$2</a>
- <a href="$2">$1</a>
- class MakeItLink {
- protected function _link_www( $matches ) {
- $url = $matches[2];
- $url = MakeItLink::cleanURL( $url );
- if( empty( $url ) ) {
- return $matches[0];
- }
- return "{$matches[1]}<a href='{$url}'>{$url}</a>";
- }
- public function cleanURL( $url ) {
- if( $url == '' ) {
- return $url;
- }
- $url = preg_replace( "|[^a-z0-9-~+_.?#=!&;,/:%@$*'()x80-xff]|i", '', $url );
- $url = str_replace( array( "%0d", "%0a" ), '', $url );
- $url = str_replace( ";//", "://", $url );
- /* If the URL doesn't appear to contain a scheme, we
- * presume it needs http:// appended (unless a relative
- * link starting with / or a php file).
- */
- if(
- strpos( $url, ":" ) === false
- && substr( $url, 0, 1 ) != "/"
- && !preg_match( "|^[a-z0-9-]+?.php|i", $url )
- ) {
- $url = "http://{$url}";
- }
- // Replace ampersans and single quotes
- $url = preg_replace( "|&([^#])(?![a-z]{2,8};)|", "&$1", $url );
- $url = str_replace( "'", "'", $url );
- return $url;
- }
- public function transform( $text ) {
- $text = " {$text}";
- $text = preg_replace_callback(
- '#(?])(()?([w]+?://(?:[w\x80-\xff#$%&~/-=?@[](+]|[.,;:](?![s<])|(?(1))(?![s<])|)))*)#is',
- array( 'MakeItLink', '_link_www' ),
- $text
- );
- $text = preg_replace( '#(<a>]+?>|>))<a>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $text );
- $text = trim( $text );
- return $text;
- }
- }