+/*
+ Copyright (C) 2011-2014 jeanfi@gmail.com
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA
+ */
+
+#include <string.h>
+
+#include <pstr.h>
+
+char *strrep(char *str, const char *old, const char *new)
+{
+ char *p, *res;
+ int pos;
+
+ if (!str)
+ return NULL;
+
+ if (!*str || !old || !*old || !new || !strcmp(old, new))
+ return str;
+
+ p = strstr(str, old);
+
+ if (!p)
+ return str;
+
+ res = malloc(strlen(str) + (new ? strlen(new) : 0) - strlen(old) + 1);
+
+ pos = p - str;
+
+ strncpy(res, str, pos);
+ res[pos] = '\0';
+
+ if (new)
+ strcat(res + pos, new);
+
+ strcat(res, str + pos + strlen(old));
+
+ return res;
+}
+
+/*
+ Derivated from http://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c
+*/
+char *strrepg(char *orig, const char *rep, const char *with) {
+ char *result; // the return string
+ char *ins; // the next insert point
+ char *tmp; // varies
+ int len_rep; // length of rep
+ int len_with; // length of with
+ int len_front; // distance between rep and end of last rep
+ int count; // number of replacements
+
+ if (!orig)
+ return NULL;
+ if (!rep)
+ rep = "";
+ len_rep = strlen(rep);
+ if (!with)
+ with = "";
+ len_with = strlen(with);
+
+ ins = orig;
+ for(count = 0; (tmp = strstr(ins, rep)); count++) {
+ ins = tmp + len_rep;
+ }
+
+ // first time through the loop, all the variable are set correctly
+ // from here on,
+ // tmp points to the end of the result string
+ // ins points to the next occurrence of rep in orig
+ // orig points to the remainder of orig after "end of rep"
+ tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
+
+ if (!result)
+ return NULL;
+
+ while (count--) {
+ ins = strstr(orig, rep);
+ len_front = ins - orig;
+ tmp = strncpy(tmp, orig, len_front) + len_front;
+ tmp = strcpy(tmp, with) + len_with;
+ orig += len_front + len_rep; // move to next "end of rep"
+ }
+ strcpy(tmp, orig);
+ return result;
+}