Forum Moderators: coopster

Message Too Old, No Replies

rewrite html to have links open in new window

need to figure out how to rewrite links in html code to open in new windows

         

gilahacker

7:24 pm on Apr 11, 2005 (gmt 0)

10+ Year Member



i.e.

$text = '<a href="www.webmasterworld.com">please click here</a> to visit webmasterworld';
echo rewritelinks($text);

which would give you this:

<a href="www.webmasterworld.com" target="_blank">please click here</a> to visit webmasterworld'

now I just gotta figure out the magic function I'm calling rewritelinks()

Reason for this is that I allow people to post things on my site, but I want any links that they post to be re-written to open in a new window.

•function is going to have to be recursive to catch multiple links in a single block of text

•function is going to have to accout for people putting in their own "target=" destinations and removing them.

•function should also keep any other attributes the link may have (css styles, etc.)

so basically we don't want to fully rewrite the link, but just check if there's a "target=", if so remove it, then tack in a "target='blank'"

I don't really want someone to just write my function for me, rather I'd like to be pointed in the right direction so I can learn myself.

Thanks,
-Jason

gettopreacherman

7:43 pm on Apr 11, 2005 (gmt 0)

10+ Year Member



Regular Expressions...Parse the string by a regex looking for the url.

gilahacker

8:01 pm on Apr 11, 2005 (gmt 0)

10+ Year Member



ok, think I found something at that php manual website we all know about (whose url I cannot mention).

<?php
$body = preg_replace('/\s(\w+:\/\/)(\S+)/', ' <a href="\\1\\2" target="_blank">\\1\\2</a>', $body);
?>

and for urls starting with www., i use...

<?php
$body = preg_replace('/\s(www\.)(\S+)/', ' <a href="http://\\1\\2" target="_blank">\\1\\2</a>', $body);
?>

haven't had a chance to try it out yet, this stuff looks a little confusing at the moment, I'm not familiar with the preg_replace function but I'm going to see how it works. I'll post my final function here.

Thanks,
-Jason

coopster

8:04 pm on Apr 11, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The Regular Expression Functions (Perl-Compatible) [php.net] pages are a good start, but there are also some good links regarding regex in the Learning PHP - Books, Tutorials and Online Resources [webmasterworld.com] thread in the WebmasterWorld PHP Library.