i want to convert text links in my content page into active links using php. i tried every possible script out there, they all fine but the problem that they convert links in img src tag. they convert links everywhere and break the html code.
i find a good script that do what i want exactly but it is in javascript. it is called jquery-linkify.
you can find the script here
http://github.com/maranomynet/linkify/
the trick in the script that it convert text links without breaking the html code. i tried to convert the script into php but failed.
i cant use the script on my website because there is other scripts that has conflict with jquery.
anyone could rewrite this script for php? or at least guide me how?
thanks.
First, parse the text with an HTML parser, with something like
DOMDocument::loadHTML. Note that poor HTML can be hard to parse, and depending on the parser, you might get slightly different output in the browser after running such a function.PHP’s
DOMDocumentisn’t very flexible in that regard. You may have better luck by parsing with other tools. But if you are working with valid HTML (and you should try to, if it’s within your control), none of that is a concern.After parsing the text, you need to look at the text nodes for links and replace them. Using a regular expression is the simplest way.
Here’s a sample script that does just that:
I did not come up with that regular expression, and I cannot vouch for its accuracy. I also did not test the script, except for this above case. However, this should be more than enough to get you going.
Output:
Note that
saveHTML()adds the surrounding tags. If that’s a problem, you can strip them out withsubstr().