目录

PHP preg_split() 函数

❮ PHP 正则表达式参考

示例

使用 preg_split() 将日期拆分为其组成部分:

<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components = preg_split($pattern, $date);
print_r($components);
?>
亲自试一试 »

定义和用法

这个preg_split()函数使用正则表达式的匹配作为分隔符将字符串分解为数组。


语法

preg_split( pattern, string, limit, flags)

参数值

Parameter Description
pattern Required. A regular expression determining what to use as a separator
string Required. The string that is being split
limit Optional. Defaults to -1, meaning unlimited. Limits the number of elements that the returned array can have. If the limit is reached before all of the separators have been found, the rest of the string will be put into the last element of the array
flags Optional. These flags provide options to change the returned array:
  • PREG_SPLIT_NO_EMPTY - Empty strings will be removed from the returned array.
  • PREG_SPLIT_DELIM_CAPTURE - If the regular expression contains a group wrapped in parentheses, matches of this group will be included in the returned array.
  • PREG_SPLIT_OFFSET_CAPTURE - Each element in the returned array will be an array with two element, where the first element is the substring and the second element is the position of the first character of the substring in the input string.

技术细节

返回值: 返回一个子字符串数组,其中每个项目对应于由正则表达式的匹配项分隔的输入字符串的一部分
PHP 版本: 4+

更多示例

示例

使用 PREG_SPLIT_DELIM_CAPTURE 标志:

<?php
$date = "1970-01-01 00:00:00";
$pattern = "/([-\s:])/";
$components = preg_split($pattern, $date, -1,
PREG_SPLIT_DELIM_CAPTURE);
print_r($components);
?>
亲自试一试 »

示例

使用 PREG_SPLIT_OFFSET_CAPTURE 标志:

<?php
$date = "1970-01-01";
$pattern = "/-/";
$components = preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
亲自试一试 »

❮ PHP 正则表达式参考