PHP preg_split function

 The PHP preg_split function uses regular expressions to split a string into many different parts. You can set the total number of strings to be split. The method of use is similar to split , but additional parameter settings for other items are added (fourth Parameters), and since PHP 5.3.0, the preg_split function has replaced the split function and has become a common function that uses regular notation to split strings. After the string is split by the preg_split function, a new PHP array is finally returned .


Basic syntax of PHP preg_split

array preg_split ( string $pattern , string $subject , int $limit , int $flags )


The first parameter, $pattern, is the regular expression. Here you can set which regular expression syntax to use as the basis for string splitting. The second parameter $subject is the original string, which is the string to be split. The third parameter $limit is used to set the total number of units after splitting. It is an integer and can be omitted. The default value is -1, which means there is no split limit. If $limit is set, the preg_split function will The entire string is divided. If the number of divided units reaches the limit of $limit, the division will stop, and the last divided section will be included to the end of the string. The fourth parameter, $flags, is a major focus of the preg_split function, and it is also a selection item. The possible values ​​are as follows:
  • PREG_SPLIT_NO_EMPTY-preg_split function will only return the non-blank part.
  • PREG_SPLIT_DELIM_CAPTURE-The preg_split function will return the regular expressions in the string together.
  • PREG_SPLIT_OFFSET_CAPTURE-preg_split function will increase the offset of each string returned.
PHP 4.0.5 added PREG_SPLIT_DELIM_CAPTURE flag.
PHP 4.3.0 added PREG_SPLIT_OFFSET_CAPTURE flag.

PHP preg_split example
<?php
// Cut according to the space
$NewString1 = preg_split ("/[\s,]+/", "Welcome to Wibibi.Have a good day.");
print_r($NewString1);

echo'<br>';

//Cut each English letter apart
$NewString2 ='Welcome';
$NewString2 = preg_split ('//', $NewString2, -1, PREG_SPLIT_NO_EMPTY);
print_r($NewString2);
?>
The output of the above example
Array ( [0] => Welcome [1] => to [2] => Wibibi.Have [3] => a [4] => good [5] => day. )
Array ( [0] => W [1] => e [2] => l [3] => c [4] => o [5] => m [6] => e )
The output of the first example is quite simple, using only regular parameters and the original string, let the preg_split function directly cut each space and complete the array, the second example adds other parameters, including $limit=-1 And PREG_SPLIT_NO_EMPTY, if you are not clear about the formal expression, you can refer to the simpler explode function.

Post a Comment

0 Comments