preg_replace_callback လုပ်ဆောင်ချက်
preg_replace_callback လုပ်ဆောင်ချက်သည် callback function ကို အသုံးပြု၍ regular expression အရ ရှာဖွေခြင်းနှင့် အစားထိုးခြင်းကို ဆောင်ရွက်ပါသည်။ ပထမအကြိမ်အနေဖြင့် regular expression ကို လက်ခံပြီး၊ ဒုတိယအကြိမ်တွင် callback function ကို လက်ခံကာ၊ တတိယအကြိမ်တွင် ကိုင်တွယ်ရမည့် string ကို လက်ခံပါသည်။ Callback function သည် ကိုက်ညီမှုများ၏ array ကို ရရှိပြီး အစားထိုးမည့် string ကို ပြန်ပေးရပါမည်။
ဝါကျဖွဲ့ပုံ
preg_replace_callback(pattern, callback, subject, [limit], [count]);
နမူနာ
String ထဲရှိ ဂဏန်းအားလုံးကို ၎င်းတို့၏ စတုရန်းများဖြင့် အစားထိုးကြပါစို့-
<?php
$str = 'Numbers: 2, 4, 6';
$res = preg_replace_callback('/\d+/', function($matches) {
return $matches[0] * $matches[0];
}, $str);
echo $res;
?>
ကုဒ်ကို run ပြီးနောက် ရလဒ်-
'Numbers: 4, 16, 36'
နမူနာ
စကားလုံးအားလုံးကို အက္ခရာအကြီးများသို့ ပြောင်းလဲကြပါစို့-
<?php
$str = 'hello world';
$res = preg_replace_callback('/\b\w+\b/', function($matches) {
return strtoupper($matches[0]);
}, $str);
echo $res;
?>
ကုဒ်ကို run ပြီးနောက် ရလဒ်-
'HELLO WORLD'
နမူနာ
ဂဏန်းတစ်ခုစီကို ကွင်းချောင်းများဖြင့် ထည့်ပေးကြပါစို့-
<?php
$str = '1 2 3 4 5';
$res = preg_replace_callback('/\d+/', function($matches) {
return '('.$matches[0].')';
}, $str);
echo $res;
?>
ကုဒ်ကို run ပြီးနောက် ရလဒ်-
'(1) (2) (3) (4) (5)'
ဤအကြောင်းကိုလည်း ကြည့်ပါ
-
preg_replaceလုပ်ဆောင်ချက်၊
သည် regular expression အရ အစားထိုးခြင်းကို ဆောင်ရွက်ပေးပါသည် -
preg_matchလုပ်ဆောင်ချက်၊
သည် regular expression အရ ရှာဖွေခြင်းကို ဆောင်ရွက်ပေးပါသည်