Page 1 of 1

Regex to change links to 'click here'

Posted: Thu Feb 05, 2009 6:02 am
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

Re: Regex to change links to 'click here'

Posted: Thu Feb 05, 2009 6:37 am
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.

Re: Regex to change links to 'click here'

Posted: Thu Feb 05, 2009 6:47 am
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!