/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <string.h>
#include <pcre.h>

typedef void (*linkhandler)(const char *, const char *);

void parse(char *html, linkhandler f)
{
    int ix;
    pcre *re;
    int rc;
    int erroffset;
    int ovector[300];
    const char *error;
    const char *url;
    const char *txt;
    re = pcre_compile("(?:<a\\s+href\\s*=\\s*[\"'])([^\"']*)(?:[\"']\\s*>)([^<]*)(?:</a>)", PCRE_CASELESS+PCRE_DOTALL+PCRE_MULTILINE, &error, &erroffset, NULL);
    rc = pcre_exec(re, NULL, html, strlen(html), 0, 0, ovector, sizeof(ovector)/sizeof(int));
    ix = 0;
    while((rc = pcre_exec(re, NULL, html, strlen(html), ix, 0, ovector, sizeof(ovector)/sizeof(int))) > 0)
    {
       pcre_get_substring(html, ovector, rc, 1, &url);
       pcre_get_substring(html, ovector, rc, 2, &txt);
       f(url, txt);
       ix = ovector[1];
    }
}

void haps(const char *url, const char* txt)
{
    printf("haps: %s / %s\n", url, txt);
}

int main()
{
    parse("bla <a href=\"foobar.html\">foobar</a> bla", haps);
    parse("bla <a href=\"foo.html\">foo</a> bla <a href=\"bar.html\">bar</a> bla", haps);
    parse("bla <a  href = 'foobar.html' >foobar</a> bla", haps);
    return 0;
}
