ios escape'<'来自html标签内的字符串 - Objective-C

时间:2016-10-28 09:13:26

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

我有以下HTML字符串,它从本地db:

动态生成
<div><span>If x < 20 Then y > 20 </span><div> //NSString : dynamically generated

应该做些什么来逃避'&lt;'和'&gt;'来自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>";

这整个字符串是动态生成的,我想要任何'&lt;'和'&gt;'除了那些要转义HTML实体的人。这是使用MathJax在UIWebView中渲染数学表达式的要求。

1 个答案:

答案 0 :(得分:0)

- (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];