Conditionally Strip HTML Node - Regexp/gsub
I want to generate a search preview of an article by removing certain html nodes including the child node(s) (p开发者_C百科articularly 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.
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.
Try:
myline = line.gsub!(/(<[^>]*>)|\n|\t/s) {" "}
精彩评论