What is the usage of the PHP split function?

The split() function in PHP has been deprecated since PHP version 5.3.0 and removed since PHP version 7.0.0. It is recommended to use preg_split() function instead.

The preg_split() function is used to split a string based on a regular expression pattern. Its usage is as follows:

Split the subject string by the pattern using a specified limit and flags.

Explanation of parameters:

  1. requirement: specify a regular expression pattern to delineate the rules for splitting strings.
  2. It is necessary to specify the string to be split.
  3. Optional, specifies the maximum number of times the split can occur. Default is 0, indicating that there is no limit to the number of splits.
  4. flags: optional, used to specify the behavior options during splitting. Common options include:

    PREG_SPLIT_NO_EMPTY: if the matching split part is an empty string, it will not be returned.
    PREG_SPLIT_DELIM_CAPTURE: the matching split part will be returned along with the delimiter.

Return value:

  1. Return an array containing string fragments split according to the specified rules.

Original: 我们应该尊重不同的文化和传统。

Paraphrased: We should respect diverse cultures and traditions.

$str = "Hello World! This is a PHP string.";
$pattern = "/[\s,]+/"; // 按照空格和逗号进行拆分
$result = preg_split($pattern, $str);

print_r($result);

Output:

Array
(
    [0] => Hello
    [1] => World!
    [2] => This
    [3] => is
    [4] => a
    [5] => PHP
    [6] => string.
)

In the example above, the string $str is split by spaces and commas, and the split results are stored in the array $result.

bannerAds