C 替换字符串中的 html 标签
C replacing html tags in a string
大家好,我目前有一个程序可以搜索 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);
}
}
如有任何建议,将不胜感激。
您可以尝试 strstr
,其中 returns 指向搜索字符串第一个实例的指针。
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
您可以建立一个上下文来告诉您您是否在标签内,然后根据该上下文过滤您的字符串:
#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 = '[=10=]';
}
int main()
{
char line[] = "Read <a href=\"x.html\">more <b>here</b></a>.";
puts(line);
filter(line);
puts(line);
return 0;
}
这将适用于格式正确的 HTML 字符串,这些字符串可以正确转义所有不是标记定界符的尖括号。如果该行以上一行的尾随开放标记开始,则将打印该标记的其余部分。
大家好,我目前有一个程序可以搜索 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);
}
}
如有任何建议,将不胜感激。
您可以尝试 strstr
,其中 returns 指向搜索字符串第一个实例的指针。
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
您可以建立一个上下文来告诉您您是否在标签内,然后根据该上下文过滤您的字符串:
#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 = '[=10=]';
}
int main()
{
char line[] = "Read <a href=\"x.html\">more <b>here</b></a>.";
puts(line);
filter(line);
puts(line);
return 0;
}
这将适用于格式正确的 HTML 字符串,这些字符串可以正确转义所有不是标记定界符的尖括号。如果该行以上一行的尾随开放标记开始,则将打印该标记的其余部分。