PHP preg_match()ฟังก์ชั่น
ตัวอย่าง
ใช้นิพจน์ทั่วไปเพื่อค้นหา "w3schools" โดยไม่พิจารณาตัวพิมพ์เล็กและตัวพิมพ์ใหญ่ในสตริง:
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo
preg_match($pattern, $str);
?>
ความหมายและการใช้งาน
ฟังก์ชันpreg_match()
จะคืนค่าว่าพบการจับคู่ในสตริงหรือไม่
ไวยากรณ์
preg_match(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:
|
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 |
รายละเอียดทางเทคนิค
คืนมูลค่า: | คืนค่า 1 หากพบการจับคู่ 0 หากไม่พบรายการที่ตรงกันและเป็นเท็จหากเกิดข้อผิดพลาด |
---|---|
รุ่น PHP: | 4+ |
บันทึกการเปลี่ยนแปลง: | PHP 7.2 - เพิ่มการตั้งค่าสถานะ PREG_UNMATCHED_AS_NULL PHP 5.3.6 - ฟังก์ชันจะคืนค่าเท็จเมื่อออฟเซ็ตยาวกว่าความยาวของอินพุต PHP 5.2.2 - รูปแบบย่อยที่มีชื่อสามารถใช้ (?'name') และ (? <name>) ไวยากรณ์นอกเหนือจากก่อนหน้า (?P<name>) |
ตัวอย่างเพิ่มเติม
ตัวอย่าง
ใช้ PREG_OFFSET_CAPTURE เพื่อค้นหาตำแหน่งในสตริงอินพุตที่พบที่ตรงกัน:
<?php
$str = "Welcome to W3Schools";
$pattern = "/w3schools/i";
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
❮ การอ้างอิง PHP RegExp