0

I'm trying to write a ruby script to turn a small markup language I wrote into HTML, but I can't figure out how to parse links. It's basically a trimmed down version of BBCode, so for example, if someone enters [i]{text}[/i], I use [i]{text}[/i].gsub('[i]','<i>').gsub('[/i]','</i>'. I can't figure out how to parse links, though. How would I turn [url=website.com]site[/url] into <a href="website.com">site</a>? I'm not using a premade BBCode parser because there are a few tags that are different, and I don't want people to use some of the tags such as [img][/img].

Orcris
  • 3,135
  • 6
  • 24
  • 24

2 Answers2

0

Very naïvely:

s.gsub(/\[url=(.*?)\](.*?)\[\/url\]/) { "<a href='#{$1}'>#{$2}</a>" }

HTML injection would be quite easy. The point here (write a proper parser) still applies to what you're doing.

Community
  • 1
  • 1
kch
  • 77,385
  • 46
  • 136
  • 148
0

I agree with kch by using a regular expression but if you want to wrap your head around it using gsub() like you've been doing...

s = "[url=website.com]site[/url]"
s2 = s.gsub('[url=','<a href="').gsub('[/url]','</a>').gsub(']','">')
rbnewb
  • 575
  • 5
  • 6