Skip to content

Instantly share code, notes, and snippets.

@vijayanandrp
Last active August 24, 2017 18:18
Show Gist options
  • Save vijayanandrp/2f4e7e9a81eeb54d7e38559a63e49ec0 to your computer and use it in GitHub Desktop.
Save vijayanandrp/2f4e7e9a81eeb54d7e38559a63e49ec0 to your computer and use it in GitHub Desktop.
text to url - converting to <img> and <a> tag in html
def linkify(html):
check = ['https://', 'http://', 'www.', '.jpg', '.png', '.jpeg', '.gif']
html_source = html
replace = {}
text = []
for letter in html:
if letter == '>':
start = True
continue
elif letter == '<':
start = False
full_text = ''.join(text)
full_text = full_text.replace('\n', '').strip()
if '//' == full_text[:2]:
full_text = full_text[2:]
total = len(full_text)
if full_text and total:
if any(n in full_text for n in check)and total > 4:
if any(n in full_text[-4:] for n in ['.jpg', '.png', '.jpeg', '.gif']):
image_tag = '<img src={} height="150" width="150"></img>'.format(full_text)
replace[full_text] = image_tag
elif total > 9 and any(n in full_text[:9] for n in ['https://', 'http://', 'www.']):
if 'www' == full_text[:3]:
change_text = 'http://' + full_text
anchor_tag = '<a href="{}">{}</a>'.format(change_text, full_text)
else:
anchor_tag = '<a href="{}">{}</a>'.format(full_text, full_text)
replace[full_text] = anchor_tag
else:
print(full_text)
text = []
if start:
text.append(letter)
for key in replace:
html_source = html_source.replace(key+'<', replace[key]+'<')
return html_source
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment