I’ve been working on a little project, and I find myself in a position where I need a php function which can linkify URLs in my data, while enabling me to set some exceptions on links I don’t want to linkify. Any idea of how to do this?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I have an open source project on GitHub: LinkifyURL which you may want to consider. It has a function:
linkify()which plucks URLs from text and converts them to links. Note that this is not a trivial task to do correctly! (See: The Problem With URLs – ands be sure to read the thread of comments to grasp all the things that can go wrong.)If you really need to NOT linkify specific domains (i.e. vimeo and youtube), here is a modified PHP function
linkify_filtered(in the form of a working test script) that does what you need:This employs a callback function to do the filtering. Yes, the regex is complex (but so it the problem as it turns out!). You can see the interactive Javascript version of
linkify()in action here: URL Linkification (HTTP/FTP).Also, John Gruber has a pretty good regex to do linkification. See: An Improved Liberal, Accurate Regex Pattern for Matching URLs. However, his regex suffers catastrophic backtracking under certain circumstances. (I’ve written to him about this, but he has yet to respond.)
Hope this helps! 🙂