Page 1 of 1

Replacing hyperlinks

Posted: Wed Oct 17, 2007 1:26 am
by Mr Tech
I still cannot get my head around regex. So frustrating!

I need to replace something like this:

Code: Select all

<a target="_blank" href="page.html" class="link">
With this:

Code: Select all

<a target="_blank" href="#" class="link">
Any ideas?

Posted: Wed Oct 17, 2007 1:34 am
by Kieran Huggins
If I understand what you're trying to do, a better solution might be to "return false" from your link's onclick() handler. Returning false keeps the click event from following the link.

Posted: Wed Oct 17, 2007 10:05 am
by John Cartwright

Code: Select all

preg_replace('#href="[^"]+#im', 'href="#"', $source);
Untested

Posted: Wed Oct 17, 2007 6:33 pm
by Mr Tech
That code worked! Thanks!

Also, thanks Kieran as that is a great idea :)

Posted: Thu Oct 18, 2007 2:35 am
by Mr Tech
Little old me again...

Normally you can use $1 to put whatever the value of the [^"] is but it isn't working in this case. Am I doing something wrong. Here's my code...

Code: Select all

$template = preg_replace('#src="[^"]+#im', "src=\"http://www.domain.com/$1", $template);

Posted: Thu Oct 18, 2007 3:05 am
by Kieran Huggins
capturing parentheses are the round kind, the square ones are character classes