简体   繁体   English

如何防止变量中的特殊字符导致html错误

[英]How to prevent the special characters in variables from causing html errors

I have a C file which generates an html script. 我有一个生成HTML脚本的C文件。 sprintf(buf, " { text: \\\\"%s (%s)\\\\",var1,var2) sprintf(buf,“ {文本:\\\\”%s(%s)\\\\“,var1,var2)

and the problem is that var2 is a string like = test>1 . 问题是var2是一个字符串,例如= test> 1。 This is being confused as the closing bracket of some other opening angular bracket in the script. 这被混淆为脚本中某些其他打开尖括号的关闭括号。

I want the data as such. 我想要这样的数据。 But I want to know whether it is possible to avoid this issue with the help of some escape character or something. 但是我想知道是否可以借助一些转义符或其他东西来避免此问题。

Just replace those special characters with HTML entities: 只需将这些特殊字符替换为HTML实体即可:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static size_t encode_len(const char *s)
{
    size_t len = 0;

    while (*s) {
        if (*s == '&' || *s == '"' || *s == '<' || *s == '>') {
            len += 5;
        } else {
            len += 1;
        }
        s++;
    }
    return len;
}

static char *encode(const char *s)
{
    char *p = malloc(encode_len(s) + 1);
    char *r = p;

    if (p == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    while (*s) {
        switch (*s) {
            case '&': memcpy(p, "&#38;", 5); p += 5; break;
            case '"': memcpy(p, "&#34;", 5); p += 5; break;
            case '<': memcpy(p, "&#60;", 5); p += 5; break;
            case '>': memcpy(p, "&#62;", 5); p += 5; break;
            default: *p++ = *s;
        }
        s++;
    }
    *p = '\0';
    return r;
}

int main(void)
{
    char *demo = "Text &\"<>";
    char *result = encode(demo);

    printf("%s = %s\n", demo, result);
    free(result);
    return 0;
}

Output: 输出:

Text &"<> = Text &#38;&#34;&#60;&#62;

If you use the less than or greater than symbol(special characters) in the html file then it will mix them with the tags. 如果您在html文件中使用小于或大于符号(特殊字符),则它将与标记混合。 So in your case try to use the html entities name to use the special characters to generate your html file. 因此,在您的情况下,请尝试使用html实体名称来使用特殊字符来生成html文件。
For reference visit: http://www.w3schools.com/html/html_entities.asp 供参考,请访问: http : //www.w3schools.com/html/html_entities.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM