views:

28

answers:

3

Hi

I want to generate a search preview of an article by removing certain html nodes including the child node(s) (particularly headers and images) and removing all other tags eg. paragraph while leaving child nodes.

e.g.

"<h2>Subject</h2><p>Subject is the who, what, where, why and when.</p>".gsub(/<\/?[^>]*>/, '')

results in

Subject Subject is the who, what, where, why and when.

however I require

Subject is the who, what, where, why and when.

I'm using the Rails plugin Loofah to sanitize user input and this works great; in fact I can define a scrubber to do this however it seems that a regexp would be sufficient for this simple operation.

Thanks in advance for any advice.

A: 

I don't get it, you want to replace the second word Subject with nothing?

Because you have 2 times Subject in your code?

Jordy
You don't need to answer questions you don't get, generally do the opposite. :)
mark
+1  A: 

Use several regexps:

"<h2>Subject</h2><p>Subject is the who, what, where, why and when.</p>".
    gsub(/<h\d>[^>]*>/,'').
    gsub(/<img[^>]*>/,'').
    gsub(/<\/?[^>]*>/, '')

It should be noted however that you are reaching the limits of complexity of what regexp can handle in processing html. If you need to do anything even more complicated (like removing based on class name etc.) then you should really be using a html parser.

slebetman
Thanks! This works great though thought a single regexp would be possible. As you say, I think I might just use Loofah.
mark
A: 

myline = line.gsub!(/(<[^>]*>)|\n|\t/s) {" "}

Cori