简体   繁体   中英

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) (particularly headers and images) and removing all other tags eg. paragraph while leaving child nodes.

eg

"<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.

尝试:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM