【问题标题】:String replacement in iOS for HTML tagsiOS中HTML标签的字符串替换
【发布时间】:2014-06-05 10:07:34
【问题描述】:

我正在为iOS 中的UIWebview 解析一个字符串。

我有一个数据 -

<p>The post <a rel="nofollow" href="http://www.someurl.com/bikes/triumph-motorcycles-plans-sell-2700-units-2015-16/">Triumph Motorcycles Plans To Sell Over 2700 Units By 2015-16</a> appeared first on <a rel="nofollow" href="http://www.someurl.com">MotorBuzz -  Car Bike News &amp; Reviews</a>.</p>

我想要的是删除文本的超链接。我不想删除文本我只想禁用文本的超链接。

所以对于上面的数据,它应该看起来像 -

 <p>The post Triumph Motorcycles Plans To Sell Over 2700 Units By 2015-16 appeared first on MotorBuzz -  Car Bike News &amp; Reviews.</p>

所以请让我知道 iOS/Objective -C 中的任何正则表达式或任何字符串替换解决方案。

谢谢。

【问题讨论】:

    标签: ios regex uiwebview nsstring


    【解决方案1】:

    您可以使用NSAttributedString。首先将 html 字符串转换为 NSAttributedString,然后从中获取实际字符串。

    NSString *html = @"<p>The post <a rel=\"nofollow\" href=\"http://www.someurl.com/bikes/triumph-motorcycles-plans-sell-2700-units-2015-16/\">Triumph Motorcycles Plans To Sell Over 2700 Units By 2015-16</a> appeared first on <a rel=\"nofollow\" href=\"http://www.someurl.com\">MotorBuzz -  Car Bike News &amp; Reviews</a>.</p>";
    
       NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding]
                                                                          options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                                    NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                               documentAttributes:nil error:nil];
        NSString *actualString= [attrString string];
    

    但它会从字符串中删除所有的html标签。

    【讨论】:

      【解决方案2】:

      幸运的是,由于您有这么简单的要求,我可以跳过整个 don't use regex to parse html 的内容,直接进入解决方案。

      匹配这个:

      <a( [^>]*?)?>|</a>
      

      并用任何内容替换它,这将删除所有锚标记。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-20
        • 1970-01-01
        • 2016-08-29
        • 1970-01-01
        • 2011-06-09
        • 1970-01-01
        相关资源
        最近更新 更多