Reputation: 630
How to modify this function so it could add target="_blank"
attribute to external links?
Take the default domain as example.com
function makeLinks($text){
if(eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text) != $text){
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1">\\1</a>', $text);
return $text;
}
$text = eregi_replace('(www\.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="http://\\1">\\1</a>', $text); // ([[:space:]()[{}]) deleted from beginnig of regex
$text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '<a href="mailto:\\1">\\1</a>', $text);
return $text;
}
Upvotes: 0
Views: 280
Reputation: 2764
<?php
class HtmlLinkUtility
{
public static $BaseDomain = null;
public static function ReplaceEmailToHtmlLink($source)
{
return preg_replace('/([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})/i',
'<a href="mailto:\1">\1</a>', $source);
}
public static function ReplaceUrlToHtmlLink($source)
{
function replaceUrl($groups) {
$url = $groups[1];
return '<a href="' . $url . '"' . (strpos($url, HtmlLinkUtility::$BaseDomain) !== false ?
' target="_blank"' : '') . '>' . $url . '</a>';
}
return preg_replace_callback('!(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)!i',
replaceUrl, $source);
}
public static function ReplaceTextDataToLinks($source, $baseDomain)
{
self::$BaseDomain = $baseDomain;
return self::ReplaceUrlToHtmlLink(self::ReplaceEmailToHtmlLink($source));
}
}
echo HtmlLinkUtility::ReplaceTextDataToLinks(
"[email protected]<br />http://www.google.com/<br />http://www.test.com/",
"google.com"
);
?>
Could not see why you would use two expressions that basically matched/replaced the same thing. Simplified your method a little.
Also, for the record. HTML is not regular in that way that it in any form could be parsed by a regular expression. Though, for simple cases like the one above, it works well.
Upvotes: 1
Reputation: 5240
Parsing HTML is unestable, expensive and, in a word, a hell. You should use Simple HTML DOM Parser.
Upvotes: 2