Open In App

PHP | preg_split() Function

The preg_split() function is an inbuilt function in PHP which is used to convert the given string into an array. The function splits the string into smaller strings or sub-strings of length which is specified by the user. If the limit is specified then small string or sub-strings up to limit return through an array. The preg_split() function is similar to explode() function but the difference is used to the regular expression to specify the delimiter but explode is not used it. 

Syntax:



array preg_split( $pattern, $subject, $limit, $flag )

Parameter: This function accepts four parameters as mentioned above and described below:

Return Value: This function returns an array after the split boundaries matched. When the limit of the original array or string exceeds then returns with an array element otherwise it’s False. Below programs illustrate the preg_split() function in PHP: 



Program 1: 




<?php
 
// Input string
$inputstrVal  = 'Geeksarticle';
 
// Implementation of preg_split() function
$result = preg_split('//', $inputstrVal , -1, PREG_SPLIT_NO_EMPTY);
 
// Display result
print_r($result);
?>

Output:
Array
(
    [0] => G
    [1] => e
    [2] => e
    [3] => k
    [4] => s
    [5] => a
    [6] => r
    [7] => t
    [8] => i
    [9] => c
    [10] => l
    [11] => e
)

Program 2: 




<?php
 
// PHP program of preg_split() function
// split the phrase by any number of commas
// space characters include \r, \t, \n and \f
 
$result = preg_split("/[\s,]+/", "Geeks for Geeks");
 
// Display result
print_r($result);
?>

Output:
Array
(
    [0] => Geeks
    [1] => for
    [2] => Geeks
)

Program 3: 




<?php
 
// PHP program to implementation of
// preg_split() function
 
// Input original string
$inputstrVal = "http://php.net/archive/2018.php";
$patternstrVal= "/[http:\/\/|\.]/";
 
// Implement preg_split() function
$result = preg_split($patternstrVal, $inputstrVal, 0,
   PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);
 
// Display result
print_r($result );
?>

Output:
Array
(
    [0] => Array
        (
            [0] => ne
            [1] => 11
        )

    [1] => Array
        (
            [0] => arc
            [1] => 15
        )

    [2] => Array
        (
            [0] => ive
            [1] => 19
        )

    [3] => Array
        (
            [0] => 2018
            [1] => 23
        )

)

Reference: http://php.net/manual/en/function.preg-split.php


Article Tags :