html - PHP autolink if not already linked -


my question similar question:

how mimic stackoverflow auto-link behavior

however solution doesn't work mixed content may contain links - urls inside of tags <a href="http://stackoverflow.com">my link</a> being mangled <a href="<a href="http://stackoverflow.com">stackoverflow.com</a>">my link</a>

here's desired behavior:

before

https://stackoverflow.com/ wonderful url.  <a href="https://stackoverflow.com/">has been linked.</a> 

after

<a href="https://stackoverflow.com/">https://stackoverflow.com/</a> wonderful url.  <a href="https://stackoverflow.com/">has been linked.</a> 

load string html in ta dom parser, iterate on text nodes, , check url. make sure text node's parent isn't <a> tag, know text you're getting not in link. now, find of urls, convert them <a> tags, , replace them in dom:

$doc = new domdocument(); $doc->loadhtml( $str);  $xpath = new domxpath($doc); foreach( $xpath->query('//text()') $text) {     if( !($text->parentnode->tagname == "a")) {         $frag = $doc->createdocumentfragment();         $frag->appendxml( preg_replace('#(http://stackoverflow.com/)#', '<a href="$1">$1</a>', $text->data));         $text->parentnode->replacechild( $frag, $text);     } } 

note relies on regex identify urls, difficult task. suggest finding 1 suits needs, using:

#(http://stackoverflow.com/)# 

however, given input:

http://stackoverflow.com/ wonderful url.  <a href="http://stackoverflow.com/">has been linked.</a>  <a href="http://stackoverflow.com/">http://stackoverflow.com/</a> 

it produces output:

<p><a href="http://stackoverflow.com/">http://stackoverflow.com/</a> wonderful url.   <a href="http://stackoverflow.com/">has been linked.</a>   <a href="http://stackoverflow.com/">http://stackoverflow.com/</a></p> 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -