Hàm preg_split () trong PHP
Thí dụ
Sử dụng preg_split () để chia một ngày thành các thành phần của nó:
<?php
$date = "1970-01-01 00:00:00";
$pattern = "/[-\s:]/";
$components =
preg_split($pattern, $date);
print_r($components);
?>
Định nghĩa và Cách sử dụng
Hàm preg_split()
ngắt một chuỗi thành một mảng bằng cách sử dụng các trận đấu của một biểu thức chính quy làm dấu phân cách.
Cú pháp
preg_split(pattern, string, limit, flags)
Giá trị tham số
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:
|
Chi tiết kỹ thuật
Giá trị trả lại: | Trả về một mảng các chuỗi con trong đó mỗi mục tương ứng với một phần của chuỗi đầu vào được phân tách bằng một khớp của biểu thức chính quy |
---|---|
Phiên bản PHP: | 4+ |
Các ví dụ khác
Thí dụ
Sử dụng cờ 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);
?>
Thí dụ
Sử dụng cờ PREG_SPLIT_OFFSET_CAPTURE:
<?php
$date = "1970-01-01";
$pattern = "/-/";
$components =
preg_split($pattern, $date, -1,
PREG_SPLIT_OFFSET_CAPTURE);
print_r($components);
?>
❮ Tham khảo PHP RegExp