separate a HTML-tag in a hash

D

Dirk Einecke

Hi.

Is there a simple way to separate a HTML-tag in a hash?

Initial situation:
<input type="text" name="test" size="20" style="border: 1px; color: red;" />

What I need:
h["tagName"] -> "input"
h["type"] -> "text"
h["name"] -> "test"
h["size"] -> "20"
h["style"] -> "border: 1px; color: red;"

Any ideas or hints?

greetings
Dirk Einecke
 
A

Alex McHale

Ok this is really rough around the edges and I'm sure has a bug hiding
in it, but on your sample there it works fine. It also works for
single tags (like checked and last in my example below). This is a
Q&D 2 minute job, I'm sure you or someone else can refine it.

#!/usr/local/bin/ruby

def explode_tag tag
return nil unless tag.is_a? String

hash = Hash.new
unless tag.sub!(/<([^\s]+) /, '').nil?
hash['tagName'] = $1
hash[$1] = $2 until tag.sub!(/([^\s]+)\s*=\s*"([^"]*)"\s*/, '').nil?
hash[$1] = true until tag.sub!(/([^\s\/<>]+)(\s+|\/|>)/, '').nil?
end
hash
end

s = '<input type="text" name="test" size="20" checked style="border:
1px; color: red;" last/>'
h = explode_tag(s)
puts h.inspect


Also don't be afraid to tell him this is crap! =)

Alex McHale
 
D

Dirk Einecke

Hi Alex.

Thank you for the script. That's exactly that what I need.

greetings
Dirk Einecke
 
A

Alex McHale

No problem. Please let me know if you find any bugs. I plan on using
this function for a project I'm working on.

Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top