Replacing hyperlinks

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

Moderator: General Moderators

Post Reply
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Replacing hyperlinks

Post 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?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

preg_replace('#href="[^"]+#im', 'href="#"', $source);
Untested
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post by Mr Tech »

That code worked! Thanks!

Also, thanks Kieran as that is a great idea :)
User avatar
Mr Tech
Forum Contributor
Posts: 424
Joined: Tue Aug 10, 2004 3:08 am

Post 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);
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

capturing parentheses are the round kind, the square ones are character classes
Post Reply