Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP – จับคู่ Regular Expression ด้วย mb_ereg_match()

ฟังก์ชัน mb_ereg_match() ใช้ตรวจสอบว่าสตริงที่กำหนดตรงกับ regular expression pattern หรือไม่ ฟังก์ชันนี้จับคู่เฉพาะ **ต้นข้อความ** (beginning of string) ไม่จำเป็นต้องจับคู่จนจบสตริง คืนค่า true (หรือ 1) หากตรงกัน และ false (หรือ 0) หากไม่ตรง

รูปแบบการใช้งาน (Syntax)

bool mb_ereg_match(string $pattern, string $string, string $options = "")

พารามิเตอร์

  • $pattern – Regular expression pattern
  • $string – สตริงที่ต้องการทดสอบ
  • $options – ตัวเลือกการค้นหา

ค่าที่คืนกลับ

คืน true (1) หากสตริงตรงกับ pattern ตั้งแต่ต้น คืน false (0) หากไม่ตรง

ตัวอย่าง 1: การจับคู่พื้นฐาน

<?php
// คืน true เพราะ 'H' อยู่ต้นสตริง
$result = mb_ereg_match("H", "Hello World");
var_dump($result);

// คืน false เพราะ 'H' ไม่อยู่ต้นสตริง
$output = mb_ereg_match("H", "World");
var_dump($output);
?>

ผลลัพธ์

bool(true)
bool(false)

หมายเหตุ: ฟังก์ชันนี้จับคู่เฉพาะต้นสตริง หากต้องการจับคู่ที่ตำแหน่งไหนก็ได้ในสตริง ให้ใช้ wildcard และ repeat operators เช่น .* ดูตัวอย่างถัดไป

ตัวอย่าง 2: ใช้ Wildcard เพื่อจับคู่ที่ตำแหน่งไหนก็ได้

<?php
$result = mb_ereg_match(".*e", "Hello World");
var_dump($result);
?>

ผลลัพธ์

bool(true)