StepCoding

ฟังก์ชัน Matching

อ่าน [1280] หมวดหมู่: Perl-Compatible

ฟังก์ชัน preg_match() เป็นฟังก์ชันในการค้นหา (matching) regular expression) ของ perl-compatible ซึ่งรูปแบบการใช้งานพารามิเตอร์ของมันนั้นมีลักษณะเช่นเดียวกับฟังก์ชัน ereg()

# รูปแบบ
$found = preg_match(pattern, string [, captured ]);
โดยที่
	$found คือ ตัวแปรที่เก็บค่าว่าข้อความที่ส่งไป match กับ pattern หรือไม่
	pattern คือ regular expression ที่กำหนดเป็นรูปแบบในการค้นหา
	string คือ ข้อความที่ต้องการค้นหา
	captured คือ optional ที่เป็นตัวแปรอะเรย์ ใช้เก็บคำที่ match กับข้อความในส่วนของ subpattern
<?php
$bool = preg_match('/y.*e$/', 'Sylvie');
// true

$bool = preg_match('/y(.*)e$/', 'Sylvie', $match);
// true, $match = array('ylvie', 'lvi')
?>

ถ้าเราต้องการให้มันค้นหา (match) แบบ case-insensitive ให้ใช้ flag "i" ดังนี้

<?php
$bool = preg_match('/y.*e$/i, 'SyLvIe');
// true
?>

ผู้สนับสนุน