সাব প্যাটার্ন পুনরায় না লিখে আগের সাব প্যাটার্নকে আবার কোনো সংকেতের মাধমে ব্যবহার করাকে বলে। প্রতিটি সাব প্যাটার্নকে এক একটি ক্যাপচার গ্রুপ ধরে ক্রম অনুযায়ে ১, ২, ৩ হিসাবে ধরা হয়। অবশই প্যাটার্ন-এ সিঙ্গেল কোটো দিয়ে আটকাতে হবে।
// Subpattern
preg_match('/(php) (zend) (exam) php zend exam/', 'start php zend exam php zend exam end', $matches); //sub pattern capture group (php),(zend),(exam)
print_r($matches);
/*
Array
(
[0] => php zend exam php zend exam
[1] => php
[2] => zend
[3] => exam
)
*/
//Backreference using subpattern
preg_match('/(php) (zend) (exam) \1 \2 \3/', 'start php zend exam php zend exam end', $matches); //sub pattern capture group (php)=1,(zend)=2,(exam)=3 (for backreference)
print_r($matches);
/*
Array
(
[0] => php zend exam php zend exam
[1] => php
[2] => zend
[3] => exam
)
*/
//Backreference of (sens|respons) is the first position 1, so it is \1
preg_match_all('/(sens|respons)e and \1ibility/', "sense and sensibility", $matches);
print_r($matches);
$string = 'My String <span>55 PKR</span> is valid';
$string = preg_replace('/<(span>).+?<\/\1/', '', $string);
echo $string; // My String is valid
// Subpattern
preg_match('/(php) (zend) (exam) php zend exam/', 'start php zend exam php zend exam end', $matches); //sub pattern capture group (php),(zend),(exam)
print_r($matches);
/*
Array
(
[0] => php zend exam php zend exam
[1] => php
[2] => zend
[3] => exam
)
*/
//Backreference using subpattern
preg_match('/(php) (zend) (exam) \1 \2 \3/', 'start php zend exam php zend exam end', $matches); //sub pattern capture group (php)=1,(zend)=2,(exam)=3 (for backreference)
print_r($matches);
/*
Array
(
[0] => php zend exam php zend exam
[1] => php
[2] => zend
[3] => exam
)
*/
//Backreference of (sens|respons) is the first position 1, so it is \1
preg_match_all('/(sens|respons)e and \1ibility/', "sense and sensibility", $matches);
print_r($matches);
$string = 'My String <span>55 PKR</span> is valid';
$string = preg_replace('/<(span>).+?<\/\1/', '', $string);
echo $string; // My String is valid