DeltaTango
DeltaTango

Reputation: 891

php regex for detecting and replacing text links with anchor tags

I got this regex off of a site forum to look for links in text and replace them with html links so that they are clickable.

the problem came when someone input one of those new youtube links that look like this:

http://youtu.be/djKd189-ag2

What happens is the link is made up to the dash and then -ag2 is left on it's own.

I don't know enough about php regex to even dare alter this to add parsing the dash so I was hoping I could get some help:

$newText = preg_replace('@((http|https)://([\w-.]+)+(:\d+)?(/([\w/_.]*(\?\S+)?)?)?)@', 
             '<a href="$1" class="link1" target="_blank">$1</a>',$text);

I am guessing it's somewhere around the \S+ part

Upvotes: 0

Views: 1564

Answers (1)

Michael
Michael

Reputation: 1328

$newText = preg_replace('@((http|https)://([\w-.]+)+(:\d+)?(/([\w/_-.]*(\?\S+)?)?)?)@', 
             '<a href="$1" class="link1" target="_blank">$1</a>',$text);

You need just a '-' where it's written '[\w/_.]'

Upvotes: 2

Related Questions