Deep BlueVBScriptWMIPHPC语言JavaScriptWindows API路由器Windows函数Python | 用C语言实现PHP的urlencode函数题目好像弄错了,PHP本身就是用C语言写,所以准确来说题目应该是PHP的urlencode函数的C语言源码。在用C语言写某个程序(至于是什么程序,参见其他文章)的时候要用到PHP的urlencode函数。好在PHP是开源的,就搜索了一下PHP的源码,在php-5.3.2\ext\standard\url.c文件中找到了PHP的urlencode函数的C语言源代码,感兴趣的可以下载PHP源码看看。但是因为用到了PHP源码中的其他函数,urlencode的源代码不能直接用到C语言程序中,我参考源码修改了一下,就可以直接使用了。代码如下,s为需要urlencode的字符串,len为字符串的长度,new_length为urlencode后新字符串的长度: char *php_url_encode(char const *s, int len, int *new_length) { #define safe_emalloc(nmemb, size, offset) malloc((nmemb) * (size) + (offset)) static unsigned char hexchars[] = "0123456789ABCDEF"; register unsigned char c; unsigned char *to, *start; unsigned char const *from, *end; from = (unsigned char *)s; end = (unsigned char *)s + len; start = to = (unsigned char *) safe_emalloc(3, len, 1); while (from < end) { c = *from++; if (c == ' ') { *to++ = '+'; #ifndef CHARSET_EBCDIC } else if ((c < '0' && c != '-' && c != '.') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a' && c != '_') || (c > 'z')) { to[0] = '%'; to[1] = hexchars[c >> 4]; to[2] = hexchars[c & 15]; to += 3; #else /*CHARSET_EBCDIC*/ } else if (!isalnum(c) && strchr("_-.", c) == NULL) { /* Allow only alphanumeric chars and '_', '-', '.'; escape the rest */ to[0] = '%'; to[1] = hexchars[os_toascii[c] >> 4]; to[2] = hexchars[os_toascii[c] & 15]; to += 3; #endif /*CHARSET_EBCDIC*/ } else { *to++ = c; } } *to = 0; if (new_length) { *new_length = to - start; } return (char *) start; } 不想复制粘贴的可以直接下载源码 [download id=10] |