StepCoding

Backreferences

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

เราสามารถอ้างอิง pattern ใน pattern ก่อนหน้าได้ โดยใช้ \1 ในการอ้างอิงเนื้อหา (ข้อความที่ match) กับ subpattern แรก \2 อ้างอิง subpattern ที่สอง และไปเรื่อย ๆ เช่น

<?php
$bool = preg_match('/([[:alpha:]]+)\s+\1/', 'Paris in the the spring', $match);
// true, $match = array('the the', 'the')

// ขั้นตอนการทำงานของมัน มันจะทำการค้นหา pattern ที่ match กับ [[:alpha:]] ก่อน 
// จากนั้นมันจะเอาข้อความที่ match กับ [[:alpha:]] มาแทนที่ใน \1 ด้วย ดังนั้นมันจะทำการค้นหาดังนี้
// Paris Paris 
// in in
// the the	ส่วนนี้จะ match กับ pattern นี้ ผลจึงออกเป็น true
// spring spring
?>

ผู้สนับสนุน