phpInDev

explode

int explode ( string string, string separator, string arrayname, [ int limit ] )

Split string according to given separator and save it into local array with name arrayname. The given string will be split always where the separator is located. Separator itself will not be present in the strings placed in the array. If the separator is empty string, or it is not found in the string, the whole string will be placed in the first index of the array. Note that given separator may be of any length. It may be single character or multiple characters. If limit is given, then only up to number of limit entries will be placed in the array, with last index containing rest of the string.

The script returns the size of the array created. The size is always 1 or above, because even empty string will be placed in the first index of the array.

NOTE: The array used will not be cleared in any way before the exploding is done (due to limitations in GM). Only previous values in used indexes will be overwritten, but any other existing value will remain in the array as it is.

Example 1. using explode

{ count = explode('a|bc|def|ghij', '|', 'testvar'); show_message( "count = " + string(count) + chr(10) + "[0] = " + testvar[0] + chr(10) + "[1] = " + testvar[1] + chr(10) + "[2] = " + testvar[2] + chr(10) + "[3] = " + testvar[3] ); }

Shows message:

count = 4 [0] = a [1] = bc [2] = def [3] = ghij

Code for explode.gml

/**
 * Explode a string into array using a separator.
 *
 * String    : String to explode
 * Separator : Separator to separate the string
 * Array     : The array where to store the variable
 * Limit     : Optional limit. 0 for all values.
 */
{
    var str, sep, arr, pos, count, len, limit, i;
    
    str = argument0;
    sep = argument1;
    arr = argument2;
    
    count = string_count(sep, str);
    limit = min(argument3 - 1, count);
    
    // If no limit was given, use separator count
    if (limit < 1)
    {
        limit = count;
    }
    
    len = string_length(sep) - 1;
    
    // Get all the pieces before last
    for (i = 0; i < limit; i += 1)
    {    
        pos = string_pos(sep, str);      
        variable_local_array_set(arr, i, string_copy(str, 1, pos - 1));
        str = string_delete(str, 1, pos + len);
    }
    
    // Get last piece
    variable_local_array_set(arr, i, str);
    
    return i + 1;
}