2016-03-09 39 views
-1

美好的一天,我目前有一個程序,它搜索一個包含大量文本的HTML文件,其中包含超鏈接。目前,我只能打印整行文本,其中包括我試圖避免的原始html標記。有沒有辦法做到這一點?C替換字符串中的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); 
        } 
      } 

任何意見將不勝感激,謝謝。

+1

請顯示您的嘗試。 –

+0

請一直顯示您的研究成果。請先閱讀[問]頁面。 –

回答

2

可以建立,告訴你一個情況下,你是否是一個標籤內與否,然後基於這方面篩選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字符串正確地轉義所有不是標籤分隔符的尖括號。如果該行以前一行的尾部開放標籤開始,則該標籤的其餘部分將被打印。

+0

謝謝,這正是我想要實現的。我會研究這一點。 – user1610834

1

您可以嘗試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 
+1

'strstr'會找到完全匹配的。我認爲OP對有關所有標籤的解決方案感興趣,無論內容如何。另外:你有沒有試過你的解決方案?它也剝去了'S/N1'。 –

+0

感謝您的意見。是的,我確實只是試圖刪除html標籤。 – user1610834