PHP preg_match_all()ฟังก์ชัน
ตัวอย่าง
ค้นหาการเกิด "ain" ทั้งหมดในสตริง:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern =
"/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
ความหมายและการใช้งาน
ฟังก์ชันpreg_match_all()
ส่งคืนจำนวนการจับคู่ของรูปแบบที่พบในสตริงและเติมค่าตัวแปรด้วยรายการที่ตรงกันที่พบ
ไวยากรณ์
preg_match_all(pattern, input, matches, flags, offset)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
input | Required. The string in which the search will be performed |
matches | Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found |
flags | Optional. A set of options that change how the matches array is structured. One of the following structures may be selected:
|
offset | Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter |
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับจำนวนการแข่งขันที่พบหรือเท็จหากมีข้อผิดพลาดเกิดขึ้น |
---|---|
รุ่น PHP: | 4+ |
บันทึกการเปลี่ยนแปลง: | PHP 7.2 - เพิ่มการตั้งค่าสถานะ PREG_UNMATCHED_AS_NULL PHP 5.4 - พารามิเตอร์ที่ตรงกันกลายเป็นตัวเลือก PHP 5.3.6 - ฟังก์ชันคืนค่าเท็จเมื่อออฟเซ็ตยาวกว่าความยาวของอินพุต PHP 5.2.2 - รูปแบบย่อยที่มีชื่อสามารถใช้ (?'ชื่อ' ) และ (? <name>) ไวยากรณ์นอกเหนือจากก่อนหน้า (?P<name>) |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ใช้ PREG_PATTERN_ORDER เพื่อตั้งค่าโครงสร้างของอาร์เรย์ ที่ ตรงกัน ในตัวอย่างนี้ แต่ละองค์ประกอบในอาร์เรย์ที่ตรงกันมีการจับคู่ทั้งหมดสำหรับหนึ่งในการจัดกลุ่มของนิพจน์ทั่วไป
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern,
$str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
❮ การอ้างอิง PHP RegExp