mtaylor Posted September 2, 2008 Share Posted September 2, 2008 Hi, I have a string containing html markup. I'm trying to make links in it clickable (for when it is displayed in the browser). This is what I have so far: $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a target="_blank" href="\\1">\\1</a>', $text); $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a target="_blank" href="http://\\2">\\2</a>', $text); $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})', '<a href="mailto:\\1">\\1</a>', $text); The problem is that this obviously matches urls in (for example) image tags. I guess I only want to be matching urls that are not inside < > tags. My first though was something like >[^<]* at the beginning - that should match a closing angle bracket followed by zero or more characters which aren't opening angle brackets, right? Would that work? Link to comment https://forums.phpfreaks.com/topic/122301-hyperlinking-urls/ Share on other sites More sharing options...
effigy Posted September 2, 2008 Share Posted September 2, 2008 <pre> <?php $data = <<<DATA <img src="http://www.somewhere.com/image.jpg"> Visit www.phpfreaks.com! <a href="http://www.google.com">http://www.google.com</a> See http://www.regular-expressions.info DATA; $pieces = preg_split('/(<[^>]+>)/', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); $num_pieces = count($pieces); for ($i = 0; $i < $num_pieces; $i++) { ### Skip tags or content of <a>. if (substr($pieces[$i], 0, 1) == '<' || array_key_exists($i-1, $pieces) && substr($pieces[$i-1], 0, 3) == '<a ' ){ continue; } $pieces[$i] = preg_replace('% ( (?: (??:https?|ftp)://) | www\. ) \S+ (?<!\p{P}) ) %x', '<a href="$1">$1</a>', $pieces[$i]); } echo htmlspecialchars(join('', $pieces)); ?> </pre> Link to comment https://forums.phpfreaks.com/topic/122301-hyperlinking-urls/#findComment-631958 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.