【问题标题】:C replacing html tags in a stringC替换字符串中的html标签
【发布时间】:2016-03-09 11:48:33
【问题描述】:

大家好,我目前有一个程序可以搜索包含大量文本的 html 文件,其中包含超链接。目前,我只能打印出整行文本,其中包括我试图避免的原始 html 标签。有没有办法做到这一点?

这是我想要实现的一个示例:

html文件中的文本示例:

<a href="/cgi-bin/as-report?as=AS41299&view=2.0">S/N1</a> Blahblahblah

我想要达到的目标:

S/N1 Blahblahblah

到目前为止我的代码:

            while (!feof(fp)) {
                memset(buffer, 0, buflen+1);
                fgets(buffer, buflen, fp);

                    if (strstr(buffer, asnumber)) {
                        printf("\"%s\"\n", buffer);
                    }
            }

任何建议将不胜感激,谢谢。

【问题讨论】:

  • 请展示您的尝试。
  • 请展示您的研究成果。请先阅读How to Ask页面。

标签: html c string tags


【解决方案1】:

您可以建立一个上下文来告诉您您是否在标签内,然后根据该上下文过滤您的 sring:

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

    void filter(char *str)
    {
        char *p = str;
        int tag = 0;

        while (*str) {
            if (*str == '<') tag = 1;        
            if (!tag) *p++ = *str;        
            if (*str == '>') tag = 0;
            str++;
        }

        *p = '\0';
    }

    int main()
    {
        char line[] = "Read <a href=\"x.html\">more <b>here</b></a>.";
        puts(line);
        filter(line);
        puts(line);

        return 0;
    }

这将适用于格式正确的 HTML 字符串,这些字符串可以正确转义所有不是标记分隔符的尖括号。如果该行以前一行的结尾打开标记开头,则将打印该标记的其余部分。

【讨论】:

  • 谢谢,这就是我想要实现的。我会调查的。
【解决方案2】:

你可以试试strstr,它返回一个指向搜索字符串第一个实例的指针。

char line[] = "<a href=\"/cgi-bin/as-report?as=AS41299&view=2.0\">S/N1</a> Blahblahblah";
printf( "line = %s\n", line );
char *line_notag = strstr(line, "</a>") + strlen("</a>"); // <-- Find the first position of the html end tag </a>, then move pass that tag to get the real string.
printf( "line_notag = %s\n", line_notag ); // line_notag =  Blahblahblah

【讨论】:

  • strstr 会找到完全匹配的。我认为 OP 对剥离所有标签的解决方案感兴趣,无论内容如何。另外:您是否尝试过您的解决方案?它也会剥离S/N1
  • 感谢您的意见。是的,我确实只是想删除 html 标签。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 2011-06-09
  • 1970-01-01
相关资源
最近更新 更多