iOS程序员工具癖

ios HTML的标签的过滤

2017-10-30  本文已影响776人  贝勒老爷
话说我们的后台跟 h5真的是很懒很懒
HTML的标签的过滤需要前台处理
 #import <Foundation/Foundation.h>
 
 @interface filterHTML : NSObject
  //过滤
  /**
   * 过滤标签
   */
  +(NSString *)filterHTML:(NSString *)str;
  +(NSString *)filterHTMLImage:(NSString *)str;
 /**
  * 替换部分标签
  */
 + (NSString *)filterHTMLTag:(NSString *)str;
 
  @end

 #import "filterHTML.h"
  
@implementation filterHTML
  
 /**
   * 过滤标签
   */
  +(NSString *)filterHTML:(NSString *)str
  {
     NSScanner * scanner = [NSScanner scannerWithString:str];
     NSString * text = nil;
     while([scanner isAtEnd]==NO)
     {
         //找到标签的起始位置
         [scanner scanUpToString:@"<" intoString:nil];
         //找到标签的结束位置
         [scanner scanUpToString:@">" intoString:&text];
         //替换字符
         str  =  [str  stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
     }
     return str;
 }
 +(NSString *)filterHTMLImage:(NSString *)str{
     NSScanner * scanner = [NSScanner scannerWithString:str];
     NSString * text = nil;
     while([scanner isAtEnd]==NO)
     {
         //找到标签的起始位置
         [scanner scanUpToString:@"<img" intoString:nil];
         //找到标签的结束位置
         [scanner scanUpToString:@">" intoString:&text];
         //替换字符
         str  =  [str  stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@"【图片】"];
     }
     return str;
 }
 
 + (NSString *)filterHTMLTag:(NSString *)str {
     //替换字符
     str  =  [str  stringByReplacingOccurrencesOfString:@"&mdash;" withString:@"-"];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&ldquo;" withString:@"\""];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&rdquo;" withString:@"\""];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&rsquo;" withString:@"’"];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&lsquo;" withString:@"‘"];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&middot;" withString:@"·"];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
     str  =  [str  stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
     str  =  [str  stringByReplacingOccurrencesOfString:@"<strong>" withString:@""];
     str  =  [str  stringByReplacingOccurrencesOfString:@"</strong>" withString:@""];
     str  =  [str  stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
     return str;
     
 }
 @end

上一篇 下一篇

猜你喜欢

热点阅读