Home >Backend Development >PHP Tutorial >C仿真PHP函数 addslashes stripslashes
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) );}