iOS【去除伺服器返回資料中的html標籤,去除指定字串,替換字串】
阿新 • • 發佈:2019-02-07
一:問題
如圖中,伺服器返回的資料裡面有大串的html 但是我們只用字串,由於不想麻煩後臺修改資料。。。。(喵很為別人著想)於是自己想辦法解決。
其實解決的方法很多很多。。比如用字串的擷取方法的到range,然後根據位置來得到裡面的想要的東東。。嘎的,想想都崩潰。
還有呢用正則表示式等等。。。正則表示式,說實話這東西除了面試時候說說和學習時候用過做專案還從來沒有自己寫過,pass,於是網上搜索學習,得到了一個方法,共享給大家。
二:解決
//去掉html標籤
-(NSString *)flattenHTML:(NSString *)html {
NSScanner *theScanner;
NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
html=[html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
}
return html;
}
恩,就是上面的方法,他會把那些標籤方法(帶著< >的)直接替換成了@”” 空格,然後返還回來的就是了。