PHP preg_split()ฟังก์ชัน
ตัวอย่าง
ใช้ 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:
|
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับอาร์เรย์ของสตริงย่อยที่แต่ละรายการสอดคล้องกับส่วนของสตริงอินพุตที่คั่นด้วยการจับคู่ของนิพจน์ทั่วไป |
---|---|
รุ่น 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 RegExp