StepCoding

Pattern Flag

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

Regular expression แบบ perl-compatible ได้กำหนด flag เพื่อเป็น options ให้เรากำหนดว่าเราต้องการให้มันทำการค้นหาข้อความในลักษณะไหน เช่น flag "i" เป็นการกำหนดว่า pattern นั้น ๆ มีลักษณะเป็น case-insensitive เป็นต้น

<?php
$bool = preg_match('/cat/i', 'Stop, Catherine!');
// true

$bool = preg_match('/cat/', 'Stop, Catherine!');
// false
?>

เราไปดูกันครับว่า flag ต่าง ๆ ในภาษา Perl ที่ถูกสนับสนุนใน Perl-compatible มีอะไรบ้าง

FlagMeaning
/regexp/iMatch case-insensitive
/regexp/sเป็นการกำหนดให้ period (.) นั้น match กับอักขระอื่น ๆ ด้วยเช่น newline (\n)
/regexp/xRemove whitespace และ comment จาก pattern
/regexp/mกำหนดว่า caret (^) จะ match หลัง newline (\n) และเครื่องหมาย dollar sign ($) จะ match ก่อน newline (\n)
/regexp/eIf the replacement string is PHP code, eval( ) it to get the actual replacement string.

นอกจาก flag ที่สนับสนุนในภาษา Perl แล้ว ก็ยังมี flag เพิ่มเติมสำหรับ Perl-compatible อีก ดังนี้

FlagMeaning
/regexp/UReverses the greediness of the subpattern; * and + now match as little as possible, instead of as much as possible
/regexp/uCauses pattern strings to be treated as UTF-8
/regexp/XCauses a backslash followed by a character with no special meaning to emit an error
/regexp/ACauses the beginning of the string to be anchored as if the first character of the pattern were ^
/regexp/DCauses the $ character to match only at the end of a line
/regexp/SCauses the expression parser to more carefully examine the structure of the pattern, so it may run slightly faster the next time (such as in a loop)

เราสามารถกำหนด flag ให้กับ pattern ได้มากกว่า 1 ค่า เช่น

<?php
$message = <<< END
To: you@youcorp
From: me@mecorp
Subject: pay up

Pay me or else!
END;

preg_match ('/^subject: (.*)/im', $message, $match);
// $match[1] = "pay up";
// เนื่องจาก flag "i" หมายถึง case-insensitive
// flag "m" หมายถึงมันจะตรวจสอบจุดเริ่มต้นของข้อความในแต่ละแถว ไม่ใช่จุดเริ่มต้นของประโยค
?>

ผู้สนับสนุน