Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Different ways to split a string into array in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 260
    Comment on it

    PHP provides a lot of functions for manipulation of string and array. Many times we need to convert a string into an array to perform operations. This article demonstrate details of different functions which can be used to convert a string into an array. The details and examples of each function are given below :

     

    1. explode()

    explode() is one of the most popular function which is generally used to split a string into an array on the basis of a string delimiter. The explode() function breaks a string into substrings on the basis of specified delimiter and returns an array of substrings.

     

    Syntax : explode ($delimiter, $string, $limit)  

    $delimiter : Specifies a string which is used as separator. (Required)

    $string : Specify string which has to split.(Required)

    $limit : An integer value, which defines the number of elements in the returned array.(Optional)


    Different possible values for limit parameters are :

    limit > 0 : The array contains the limit number of elements.

    limit < 0 : The array contains all elements except the last-limit element.

    limit = 0 : O is treated as 1, The array contains one element which is complete string.


    Result : It returns an array of substrings split from the original string by delimiter. explode() returns false with empty delimiter(""). If a string does not contain the delimiter or with negative limit, It will return an empty array.


    Note : Support for negative limits were added from PHP version 5.1.0


    Example :

    <?php
    $string = "apple,orange,mango,pear";
    
    echo "<pre>";
    
    // without limit
    echo "Without limit : <br>";
    print_r(explode(',',$string));
    
    // with 0 limit
    echo "<br>With 0 limit : <br>";
    print_r(explode(',',$string,0));
    
    // with positive limit
    echo "<br>With positive limit : <br>";
    print_r(explode(',',$string,2));
    
    // with negative limit 
    echo "<br>With negative limit : <br>";
    print_r(explode(',',$string,-1));
    
    echo "</pre>";
    ?>

    Output : 

    Without limit :
    Array
    (
        [0] => apple
        [1] => orange
        [2] => mango
        [3] => pear
    )
    With 0 limit :
    Array
    (
        [0] => apple,orange,mango,pear
    )
    With positive limit :
    Array
    (
        [0] => apple
        [1] => orange,mango,pear
    )
    With negative limit :
    Array
    (
        [0] => apple
        [1] => orange
        [2] => mango
    )

     

     

    2. str_split()

    str_split() function is also used to split a string into an array. The function splits a string by each character as the default, if there is no value specified for split_length parameter.


    Syntax :  str_split($string, $split_length)

    $string : Specifies a string to split.(Required)

    $split_length : An integer value which defines the length (Number of characters) of substring. Default value equals to 1.(Optional)


    Result : str_split() also returns an array of substrings, split from the specified string. The length of each array element depends on the value passed as split_length. As default str_split() splits the string with length of 1 character.

    If split_length is less than 1, the function will return FALSE.

    If the split_length is equal or greater than the length of the string, the function will return the whole string as an only element.

     

    Example :

    <?php
    $string = "Testing PHP functions";
    
    // without split length
    echo "Without split lenght : <br>";
    print_r(str_split($string));
    
    echo "<pre>";
    
    // with split length
    echo "<br>With split lenght : <br>";
    print_r(str_split($string, 4));
    
    $string = "Hello";
    
    // with split length greater than string
    echo "<br>With split length greater than string : <br>";
    print_r(str_split($string,6));
    
    echo "</pre>";
    ?>

    Output : 

    Without split lenght :
    Array ( [0] => T [1] => e [2] => s [3] => t [4] => i [5] => n [6] => g [7] => [8] => P [9] => H [10] => P [11] => [12] => f [13] => u [14] => n [15] => c [16] => t [17] => i [18] => o [19] => n [20] => s )
    With split lenght :
    Array
    (
        [0] => Test
        [1] => ing
        [2] => PHP
        [3] => func
        [4] => tion
        [5] => s
    )
    With split length greater than string :
    Array
    (
        [0] => Hello
    )

     

     

    3. preg_split()

    Just like above function preg_split() function also split a string into substrings on the basis of regular expression and return an array as a result.


    Synatx : preg_split ($expression, $string, $limit, $flags)

    $expression : A regular expression which is used as delimiter.(Required)

    $string : Specifies a string to split.(Required)

    $limit : An integer which defines the length of array elements.(Optional)

    $flags : flags defines the types of matching performed.(Optional)


    $flags can have the following values :

    PREG_SPLIT_NO_EMPTY : With this flag the preg_split() prevents the empty string and only returns the non-empty string as a result.

    PREG_SPLIT_DELIM_CAPTURE : With this flag, the function will capture and returns the substring matched in the parenthesized expression.

    PREG_SPLIT_OFFSET_CAPTURE :  With this flag, the function returns an array of the match string with its respective offset in string.

    Flags can also be used in combination using | (bitwise) operator.


    Result : preg_split() also returns an array. If a limit parameter is specified, then only string split into specified limit length. limit with values -1, 0 or NULL defines "no limit", which is useful for specifying flags.

     

    Note : On matching fails, the function return an array with single element which contains the whole string.


    Example :

    <?php
    $string = "PHP is preprocessor hypertext";
    
    echo "<pre>";
    // split the phrase by any number of space characters,
    // which include " ", \r, \t, \n and \f
    print_r(preg_split("/[\s]+/", $string));
    
    echo "<br>";
    echo "If pattern not match : <br>"
    print_r(preg_split("/\,/", $string));
    
    echo "<br>";
    
    // with Flags
    print_r(preg_split('/ /', $string, -1, PREG_SPLIT_OFFSET_CAPTURE));
    
    echo "<br>";
    
    $string = "Test";
    print_r(preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY));
    
    echo "</pre>";
    ?>

    Output : 

    Array
    (
        [0] => PHP
        [1] => is
        [2] => preprocessor
        [3] => hypertext
    )
    If pattern not match :
    Array
    (
        [0] => PHP is preprocessor hypertext
    )
    Array
    (
        [0] => Array
            (
                [0] => PHP
                [1] => 0
            )
        [1] => Array
            (
                [0] => is
                [1] => 4
            )
        [2] => Array
            (
                [0] => preprocessor
                [1] => 7
            )
        [3] => Array
            (
                [0] => hypertext
                [1] => 20
            )
    )
    Array
    (
        [0] => T
        [1] => e
        [2] => s
        [3] => t
    )

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: