iOS:从NSString中删除(一个html字符串)
So I have an NSString
which is basically an html
string with all the usual html
elements. The specific thing I would like to do is to just strip it from all the img
tags. The img
tags may or may not have max-width, style or other attributes so I do not know their length up front. They always end with />
所以我有一个NSString,它基本上是一个包含所有常用html元素的html字符串。我想要做的具体事情就是从所有img标签中删除它。 img标签可能有也可能没有max-width,style或其他属性,所以我不知道它们的长度。它们总是以/>结束
How could I do this?
我怎么能这样做?
EDIT: Based on nicolasthenoz
's answer, I came up with a solution that requires less code:
编辑:基于nicolasthenoz的答案,我想出了一个需要更少代码的解决方案:
NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag
NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""];
2 个解决方案
#1
14
You can use the NSString
method stringByReplacingOccurrencesOfString
with the NSRegularExpressionSearch
option:
您可以将NSString方法stringByReplacingOccurrencesOfString与NSRegularExpressionSearch选项一起使用:
NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])];
Or you can also use the replaceMatchesInString
method of NSRegularExpression
. Thus, assuming you have your html in a NSMutableString *html
, you can:
或者您也可以使用NSRegularExpression的replaceMatchesInString方法。因此,假设您在NSMutableString * html中有html,您可以:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>"
options:NSRegularExpressionCaseInsensitive
error:nil];
[regex replaceMatchesInString:html
options:0
range:NSMakeRange(0, html.length)
withTemplate:@""];
I'd personally lean towards one of these options over the stringByReplacingOccurrencesOfRegex
method of RegexKitLite
. There's no need to introduce a third-party library for something as simple as this unless there was some other compelling issue.
我个人倾向于使用RegexKitLite的stringByReplacingOccurrencesOfRegex方法中的一个选项。除非有其他令人信服的问题,否则没有必要为这样简单的事情引入第三方库。
更多相关文章
- 关于input的一些问题解决方法分享
- Asp.net MVC 解决:CS0308: 非泛型 方法“System.Web.Mvc.Html.Li
- html中页面传递参数不用cookie不用缓存,js方法搞定
- TP-link 无线路由器WDS设置方法图解_无线桥接设置 详细出处参考:h
- ThinkPHP生成静态页buildHtml方法
- 在新选项卡中打开下载的文件
- 我正在尝试使用带有post方法的AJAX将用户名和密码发送到php文件
- html中插入activex控件之后 需要在 网页中实现控件的属性及方法,
- iframe调用后台方法通过response返回html代码