如何以纯文本形式显示包含HTML标记的字符串

时间:2013-01-22 08:46:49

标签: iphone ios

  

可能重复:
  Remove HTML Tags from an NSString on the iPhone

我正在使用谷歌方向api在我的mapview中显示地图,它给我HTML方向字符串,其中包含HTML标记。

现在我想以纯文本显示该字符串我该怎么做。我的字符串在这里:

    Head <b>southwest</b> toward <b>GH Rd</b>
    Exit the roundabout onto <b>GH Rd</b><div style="font-size:0.9em">Go through 1 roundabout</div>
    At the roundabout, take the <b>1st</b> exit onto <b>Road Number 2</b><div style="font-size:0.9em">Pass by myonlinesearch.blogspot.com (on the left in 600&nbsp;m)</div>
    At the roundabout, take the <b>3rd</b> exit onto <b>CH Rd</b>
    At <b>Indroda Cir</b>, take the <b>2nd</b> exit onto <b>Gandhinagar Ahmedabad Rd/SH 71</b><div style="font-size:0.9em">Continue to follow Gandhinagar Ahmedabad Rd</div><div style="font-size:0.9em">Go through 1 roundabout</div>
    At the roundabout, take the <b>1st</b> exit onto <b>Sardar Patel Ring Rd</b>
    At <b>Ranasan Cir</b>, take the <b>3rd</b> exit onto <b>NH 8</b><div style="font-size:0.9em">Pass by Galaxy Restaurant (on the left in 4.3&nbsp;km)</div>
    Turn <b>left</b> onto <b>Galaxy Rd</b><div style="font-size:0.9em">Pass by Shiv Shakti Food Fort (on the left)</div>
    Turn <b>left</b> onto <b>NH 59</b>
    Turn <b>right</b><div style="font-size:0.9em">Go through 1 roundabout</div>
    Turn <b>right</b>
   Turn <b>left</b><div style="font-size:0.9em">Destination will be on the right</div>

3 个答案:

答案 0 :(得分:3)

您可以使用RegularExpression / Predicates删除&lt;之间的所有字符。 &安培; &GT;

但如果您的文字包含一些&lt;&gt;它将被删除

  NSRange range;
  NSString *string;
  while ((range = [string rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound){
    string=[string stringByReplacingCharactersInRange:range withString:@""];
  }
  NSLog(@"Un block string : %@",string);

答案 1 :(得分:0)

您必须通过解析器解析文本,只需扫描行并在那里使用替换函数就可以很容易地解析这些文本。

 [yourString stringByReplacingOccurrencesOfString:@"<b>"withString:""];
[yourString stringByReplacingOccurrencesOfString:@"</b>"withString:""];

这将为你解决问题。

答案 2 :(得分:0)

你可以选择..

-(NSString *) stringByStrippingHTML 
{
  NSRange r;
  NSString *s = [[self copy] autorelease];
  while ((r = [s rangeOfString:@"]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
    s = [s stringByReplacingCharactersInRange:r withString:@""];
  return s;
}

或者更好地使用NSString类别从字符串中删除HTML,即“GTMNSStringHTMLAdditions”。