📅  最后修改于: 2023-12-03 15:33:47.293000             🧑  作者: Mango
preg_split
是PHP中一个用于拆分字符串的函数。它使用正则表达式来定义分隔符,并将一个字符串拆分成数组。
preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] ) : array
$pattern
- 正则表达式模式来定义分隔符。$subject
- 待拆分的字符串。$limit
- 拆分的最大次数,如果未提供或为-1,则不限制次数。$flags
- 使用PREG_SPLIT_NO_EMPTY
来删除数组中的空元素,使用PREG_SPLIT_DELIM_CAPTURE
来保留分隔符。$str = "apple+bear,cat,dog";
$pattern = "/[+,]/";
$arr = preg_split($pattern, $str);
print_r($arr);
//Output: Array ( [0] => apple [1] => bear [2] => cat [3] => dog )
$str = "Hello World!";
$pattern = "/ /";
$arr = preg_split($pattern, $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);
//Output: Array ( [0] => Hello [1] => World! )
$str = "apple+bear,cat,dog";
$pattern = "/([+,])/";
$arr = preg_split($pattern, $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($arr);
//Output: Array ( [0] => apple [1] => + [2] => bear [3] => , [4] => cat [5] => , [6] => dog )
$subject
可以是多行字符串,但是不适用于UTF-8字符集。$pattern
需要使用正则表达式。$pattern
不能以反斜杠\
开头。PREG_SPLIT_DELIM_CAPTURE
标志,则在输出数组中将包含分隔符。