Page 1 of 1

How do i add anchor tags to URLs?

Posted: Tue Mar 13, 2007 9:57 am
by zoe
I'm building this site with a fairly crude little CMS, and I'm trying to figure out how, when the site owner includes a URL as part of, lets say a news article, I can recognise that it's a URL, then add anchor tags at either end. I found feyd's great intro to regex, which showed me how to recognise a URL, but after that, I'm way out of my depth here.

So far:

Code: Select all

if (preg_match("#^\w+://(www\.)?\w+\.\w+#i", $content)) {
Also, will the above find URLs within the $content string, or is it looking for the whole string to be a URL?
8O
Many, many thanks in advance. The page in question is here: http://www.marianneanderson.co.uk/new/news.php
You can see from the owner's news entry why I'd like to figure this out.

Posted: Tue Mar 13, 2007 10:10 am
by feyd
The pattern posted will look for the beginning of a line in $content to match.

I'd probably suggest using a preg_match_all(), losing the "^" anchor and altering the pattern to better find links such as

Code: Select all

~((?:https?|ftps?)://)?(?:www\.)?[a-z0-9_]+(?:\.[a-z0-9_]+)+[^\s]*~is
That's entirely untested.

Posted: Tue Mar 13, 2007 10:16 am
by zoe
Thanks very much for the reply - which has just confirmed that I'm getting way beyond myself here!
Reckon I'll just include a separate URL box for each article.