0

I have looked in vain and I need to get a some linked text and add target="_blank" to it. I can't use js as it's for a newsletter.

The linked text could be just a word or it could be a url that is linked.

I need to get the link text and the link and then recreate it with the target="_blank" in..

Any ideas?

Just to clarify. I have either: text or http://somelink.com/etc and need to add the target_blank to it without changing anything else. Js would be ideal but won't work.

I am using django and wanted to create some kind of linkify filter

Designer023
  • 1,902
  • 1
  • 26
  • 43

2 Answers2

0

Perhaps something like pyquery?

>>> from pyquery import PyQuery
>>> d = PyQuery('<a href="http://google.com">My Link</a>')
>>> print d('a').attr('target', '_blank')
<a href="http://google.com" target="_blank">My Link</a>
Brandon Konkle
  • 737
  • 5
  • 9
0

If you wan't to do it with regexp you can

>>> import re

>>> link = """<a href="somesite">This is the link to some site</a>"""

>>> e = re.sub(r'<a(?P<in_a>[^>]+)>(?P<in_link>[^<]+)</a>',
       r'<a \g<in_a> target="_blank" > \g<in_link> </a>',
       link,
       )
>>> print e
<a  href="somesite" target="_blank" > This is the link to some site </a>
Mirko Rossini
  • 409
  • 2
  • 9
  • oooh this looks useful. Cheers dude. I will give this a go as it has some more powerful uses than just replacing instances of – Designer023 Nov 19 '10 at 16:35