【问题标题】:How do I reliably convert special characters like £ to HTML equivalents using Cocoa?如何使用 Cocoa 可靠地将特殊字符(如 £)转换为 HTML 等价物?
【发布时间】:2011-11-05 06:50:30
【问题描述】:

我正在尝试为 Mail.app 提供一些简单的 html:列表、粗体、一些斜体。但是,我注意到如果我使用像£ 这样的字符,那么 Mail.app 就不会显示任何内容。我意识到我需要转换为 HTML 实体,例如 £(此处为完整列表:http://www.w3schools.com/tags/ref_entities.asp)。我有一个适用于我的用户想出的大多数角色的部分解决方案,但它远不是一个可靠的解决方案:

- (NSString*) makeValidHTML:(NSString*)str {
  str = [str stringByReplacingOccurrencesOfString:@"£" withString:@"£"];
  str = [str stringByReplacingOccurrencesOfString:@"¢" withString:@"¢"];
  str = [str stringByReplacingOccurrencesOfString:@"¥" withString:@"¥"];
  str = [str stringByReplacingOccurrencesOfString:@"©" withString:@"©"];
  str = [str stringByReplacingOccurrencesOfString:@"®" withString:@"®"];
  str = [str stringByReplacingOccurrencesOfString:@"°" withString:@"°"];
  str = [str stringByReplacingOccurrencesOfString:@"¿" withString:@"¿"];
  str = [str stringByReplacingOccurrencesOfString:@"¡" withString:@"¡"];
  str = [str stringByReplacingOccurrencesOfString:@"‘" withString:@"'"];
  str = [str stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
  str = [str stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
  str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@"""];
  str = [str stringByReplacingOccurrencesOfString:@"“" withString:@"""];
  str = [str stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
  str = [str stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
  return str;
}

有没有一种标准方法可以做到这一点,而不必列出所有可能的保留字符?

【问题讨论】:

    标签: cocoa email html-entities macos


    【解决方案1】:

    这堂课应该对你有帮助:
    https://github.com/mwaterfall/MWFeedParser/blob/master/Classes/NSString+HTML.m

    从另一个 SO 答案中检索到的链接:
    Converting &amp; to & in Objective-C

    【讨论】:

      【解决方案2】:

      我认为您的主要问题是您没有将 HTML 页面编码和声明为 UTF-8。虽然您提到的某些实体是真正的问题并且需要转换,例如 &amp;gt;&amp;gt;(链接到的代码 @Joel Martinez 将对此有所帮助),但 £ 符号之类的东西可以正常工作如果页面被声明并编码为 Unicode 格式,例如 UTF-8:

      &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt;

      【讨论】:

      • 试过这个并没有什么不同,但感谢您的建议。
      • 这实际上在服务器发送 Content-Type HTTP 标头中的字符集时不起作用,因为 HTTP 标头优先于元标头。
      猜你喜欢
      • 2012-12-03
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-09
      相关资源
      最近更新 更多