Hàm preg_split() của PHP
Ví 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);
?>
Hãy tự mình thử »Đị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 kết quả khớp của 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ả về: | 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 kết quả khớp của biểu thức chính quy |
---|---|
Phiên bản PHP: | 4+ |
Thêm ví dụ
Ví 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);
?>
Hãy tự mình thử »Ví 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);
?>
Hãy tự mình thử »❮ Tham khảo RegExp PHP