commit f43c863610b5fde251571316519b7baab0e6ad54
parent 705ecc0f6539b834eff3d7e817f8b0d54101ee14
Author: ByteProject <stefan.vogt@byteproject.net>
Date: Sun, 8 Jan 2012 01:46:43 +0100
improved implementation of PHP's explode() function
Diffstat:
2 files changed, 79 insertions(+), 0 deletions(-)
diff --git a/ansilove/explode.c b/ansilove/explode.c
@@ -0,0 +1,47 @@
+//
+// explode.m
+// AnsiLove/C
+//
+// Copyright (c) 2011, Stefan Vogt. All rights reserved.
+// http://byteproject.net
+//
+// Use of this source code is governed by a MIT-style license.
+// See the file LICENSE for details.
+//
+
+#if defined(__APPLE__) && defined(__MACH__)
+#import "explode.h"
+#else
+#include "explode.h"
+#endif
+
+int64_t explode(char ***arr_ptr, char delimiter, char *str)
+{
+ char *src = str, *end, *dst;
+ char **arr;
+ int64_t size = 1, i;
+
+ while ((end = strchr(src, delimiter)) != NULL)
+ {
+ ++size;
+ src = end + 1;
+ }
+
+ arr = malloc(size * sizeof(char *) + (strlen(str) + 1) * sizeof(char));
+
+ src = str;
+ dst = (char *) arr + size * sizeof(char *);
+ for (i = 0; i < size; ++i)
+ {
+ if ((end = strchr(src, delimiter)) == NULL)
+ end = src + strlen(src);
+ arr[i] = dst;
+ strncpy(dst, src, end - src);
+ dst[end - src] = '\0';
+ dst += end - src + 1;
+ src = end + 1;
+ }
+ *arr_ptr = arr;
+
+ return size;
+}
+\ No newline at end of file
diff --git a/ansilove/explode.h b/ansilove/explode.h
@@ -0,0 +1,31 @@
+//
+// explode.h
+// AnsiLove/C
+//
+// Copyright (c) 2011, Stefan Vogt. All rights reserved.
+// http://byteproject.net
+//
+// Use of this source code is governed by a MIT-style license.
+// See the file LICENSE for details.
+//
+
+#if defined(__APPLE__) && defined(__MACH__)
+#import <Foundation/Foundation.h>
+#else
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+#ifndef explode_h
+#define explode_h
+
+// Converts a delimited string into a string array. Other than PHP's
+// explode() function it will return an integer of strings found. I
+// consider this as much better approach as you can access the strings
+// via array pointer and you don't have to determine how many string
+// instances were stored overall as this is what you're getting.
+
+int64_t explode(char ***arr_ptr, char delimiter, char *str);
+
+#endif