Regex to change links to 'click here'

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Regex to change links to 'click here'

Post by mattpointblank »

Hey everyone.

I've inherited a database full of articles, all of which contain enormous links which use the URL as the target, eg:

<a href="http://www.longurlgoeshere.com">http://www.longurlgoeshere.com</a>

I'd like to write a regex to just rename these to 'click here' or something - I took this code from the PHP manual:

Code: Select all

 
$content = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">\\0</a>", $content);
 
but this doesn't work properly - it breaks my link apart at the slashes and results in something like this:

<a href="%3Ca%20href=" http:="" http://www.website.com="" portal="" server.pt="" gateway="" ptargs_32_0_1851_0_-1_47="" http;="" i-collab.website.com;7001="" collab="" do="" document="" overview?projid="881618&folderID=872457"">FULL URL GOES HERE</a>"> <a href="FULL URL GOES HERE">FULL URL GOES HERE</a>

so I sort of end up with 2 links. I tried modifying the regex like so:

Code: Select all

 
$content = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
                     "<a href=\"\\0\">Click Here</a>", $content);
 
and this breaks the link altogether. Any regex wizards able to sort this one?

Cheers
Matt
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Regex to change links to 'click here'

Post by Chris Corbyn »

Don't use "click here"... that's an enormous usability no-no.

Just truncate them with "...".

Untested:

Code: Select all

$str = preg_replace('~<a href="([^"]*)">([^<]{16}).+?</a>~is', '<a href="$1">$2...</a>', $input);
Possibly use &#8230; instead of "..." too for the ellipsis.
mattpointblank
Forum Contributor
Posts: 304
Joined: Tue Dec 23, 2008 6:29 am

Re: Regex to change links to 'click here'

Post by mattpointblank »

Fantastic, worked perfectly. It didn't even occur to me that I could limit the text using a regex - thanks. I'm very much of the school of thought that 'click here' is useless, but a) the client suggested it and b) I couldn't think of an alternative. Thanks again!
Post Reply