【问题标题】:ios escape '<' from string inside html tag - Objective-Cios从html标签内的字符串中转义'<' - Objective-C
【发布时间】:2016-10-28 09:13:25
【问题描述】:

我有以下从本地数据库生成的 HTML 字符串:

<div><span>If x < 20 Then y > 20 </span><div> //NSString : dynamically generated

应该怎么做才能从 html 标签内的字符串中转义 '' 符号,以便我们得到以下输出:

<div><span>If x &lt; 20 Then y &gt; 20 </span><div>

更新

NSString *htmlString = @"<td style=\"vertical-align: top; text-align: left; width: 95%;\">\
    <span>$$If\\ \\ f(x) \\ \\ is \\ continuous \\ on \\ [0,8]\\ defined \\ as$$<br>\
    $$f(x) = x^2 +ax + 6 \\ \\ \\ \\ for \\ \\ 0 <x < 2$$<br>\
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $$= 3x +2 \\ \\ \\ \\ \\ \\ for \\ 2<x<4$$<br>\
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $$= 2ax + 5b \\ \\ \\ \\ \\ \\ \\ for \\ 2<x<8$$<br>\
                Find <em>a</em>&nbsp;and <em>b</em></span>\
    </td>";

这整个字符串是动态生成的,我希望任何 '' 除了带有 HTML 实体的那些被转义。这是使用 MathJax 在 UIWebView 中渲染数学表达式的要求。

【问题讨论】:

  • 尝试使用 html 解析器。
  • 请看看我有问题的更新。 html 解析器是否适用于动态 html 字符串?
  • 是的,它也适用于动态生成的html
  • 谢谢!任何工作示例或参考链接??
  • 只需在 ios html 解析器上进行谷歌搜索。

标签: ios objective-c nsstring html-escape-characters


【解决方案1】:
- (NSString *) replaceHTMLEntitiesInString:(NSString *) htmlString {
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    htmlString = [htmlString stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    return htmlString;
}

拨打htmlString = [self replaceHTMLEntitiesInString:htmlString];

【讨论】:

  • 这也将应用于 html 实体。所以它会返回:<div><span>If x < 20 然后 y > 20 </span><div>
猜你喜欢
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多