How do i add anchor tags to URLs?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
zoe
Forum Commoner
Posts: 36
Joined: Sat Jun 11, 2005 11:51 am
Location: Glasgow

How do i add anchor tags to URLs?

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
zoe
Forum Commoner
Posts: 36
Joined: Sat Jun 11, 2005 11:51 am
Location: Glasgow

Post 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.
Post Reply