源代码
c
#include "stdio.h"
#include "stdlib.h"
//防真函数,仿真php addslashes......
char* addslashes(char *str)
{
char replaceStr[] = {'\'','"','\\'};
int newStrLen=0;
for(int i = 0; i < strlen(str); ++i)
{
++newStrLen;
for(int j=0;j<strlen(replaceStr);++j)
{
if (replaceStr[j] == str[i]){
++newStrLen;
break;
}
}
}
char * retStr = (char*)malloc(newStrLen+1);
memset(retStr,'\0',newStrLen+1);
newStrLen = 0;
for(int i = 0; i < strlen(str); ++i)
{
for(int j=0;j<strlen(replaceStr);++j)
{
if (replaceStr[j] == str[i]){
memcpy(retStr+newStrLen,"\\",1);
++newStrLen;
break;
}
}
memcpy(retStr + newStrLen,&str[i],1);
++newStrLen;
}
return retStr;
}
//去掉所有的反斜杠转义符
char* stripslashes(char* str)
{
int newStrLen = 0;
char tmp;
for(int i=0; i < strlen(str);++i){
if (str[i] != '\\')++newStrLen;
}
char * retStr = (char*)malloc(newStrLen+1);
memset(retStr,'\0',newStrLen+1);
newStrLen=0;
for(int i=0; i < strlen(str);++i)
{
if (str[i]!='\\'){
memcpy(retStr + newStrLen,&str[i],1);
++newStrLen;
}
}
return retStr;
}
void main(int argc,char ** argv)
{
char * arg = argc == 1 ? argv[0] : argv[1];
arg = "2'23423423,\"111231231232\\1\"";
char * add_char = addslashes(arg);
printf("%s\n",add_char);
printf("%s\n",stripslashes(add_char) );
}
运行结果
![clipboard.png](https://i-blog.csdnimg.cn/blog_migrate/91cd3691b4ba019636a0e279e889e741.png)