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方法中的一个选项。除非有其他令人信服的问题,否则没有必要为这样简单的事情引入第三方库。

更多相关文章

  1. 关于input的一些问题解决方法分享
  2. Asp.net MVC 解决:CS0308: 非泛型 方法“System.Web.Mvc.Html.Li
  3. html中页面传递参数不用cookie不用缓存,js方法搞定
  4. TP-link 无线路由器WDS设置方法图解_无线桥接设置 详细出处参考:h
  5. ThinkPHP生成静态页buildHtml方法
  6. 在新选项卡中打开下载的文件
  7. 我正在尝试使用带有post方法的AJAX将用户名和密码发送到php文件
  8. html中插入activex控件之后 需要在 网页中实现控件的属性及方法,
  9. iframe调用后台方法通过response返回html代码

随机推荐

  1. MySQL 5.7.22 免安装配置
  2. MySQL数据库阶段学习目录
  3. 临时表空间、drop、truncate、delete的区
  4. SQL SERVER 2005 数据库对比工具,并自动生
  5. sql 内置函数 获取表的 列名
  6. 多表查询SQL中的多个计数
  7. HSQLDB / Oracle - IN子句中的1000多个
  8. PHP mysql_fetch_array得不到数据
  9. linux下mysql下载安装
  10. SQL Server中存储过程比直接运行SQL语句