အကယ်၍ သင်သည် PHP နှင့်အတူအလုပ်လုပ်နေပြီးသင်၏မူလစာသားမှကောက်နုတ်ချက်တစ်ခုကိုသာဖော်ပြလိုပြီးအက္ခရာအတော်များများတွင်ဖြတ်တောက်လိုလျှင်၎င်းကောက်နှုတ်ချက်သည်နှစ်လယ်ပိုင်းတွင်လုပ်လျှင်အရုပ်ဆိုးသွားနိုင်သည်။ ငါလုပ်ဖို့ function တစ်ခုရေးခဲ့ရတယ် ASP နှင့် ASP.NET မှာနောက်ဆုံးအက္ခရာကနေစက်ဝိုင်းစီးပြီးနောက်ဆုံးအာကာသကိုရှာပြီးအဲဒီမှာဖြတ်လိုက်တယ်။ လည်ချောင်းနာနှင့် overkill ၏နည်းနည်း။ ဒါကိုငါ့အိမ်မှာတကယ်လုပ်လို့ရတယ် စာမျက်နှာ ငါသာပထမ ဦး ဆုံးဇာတ်ကောင် 500 ပေးဘယ်မှာ။
ယနေ့ခေတ် PHP နှင့်အတူတူပင် function ကိုတီထွင်ရန်အသင့်ရှိနေသော်လည်း PHP တွင်လုပ်ဆောင်နေသော function ရှိသည် (ပုံမှန်အတိုင်း) ကိုတွေ့ရှိခဲ့သည်။ နင်.
ကုဒ်အဟောင်းသည်ပထမစာလုံးမှ substring ($ content) ကိုသင်အများဆုံးလိုချင်သောစာလုံးရေ ($ maxchars) သို့ယူသွားလိမ့်မည်။
$ content = substr ($ content, 0, $ maxchars); echo $ အကြောင်းအရာ၊
ကုဒ်အသစ်
$ content = substr ($ content, 0, $ maxchars); $ pos = strrpos ($ အကြောင်းအရာ၊ ""); if ($ pos> 0) {$ content = substr ($ content, 0, $ pos); } အကြောင်းအရာ echo;
ဒါကြောင့် code အသစ်ကသင်ရှာဖွေနေတဲ့ character limit မှာအကြောင်းအရာကိုအရင်ဖြတ်ပါ သို့သော်နောက်တစ်ဆင့်မှာအကြောင်းအရာရှိနောက်ဆုံးနေရာ (““) ကိုရှာဖွေရန်ဖြစ်သည်။ $ pos ကြောင်းအနေအထားဖြစ်ခြင်းတက်လေလိမ့်မယ်။ အခုတော့ငါ pos ကို $ pos> 0 ရှိမရှိမေးမြန်းခြင်းအားဖြင့်အကြောင်းအရာထဲမှာအာကာသရှိတကယ်တော့သေချာ။ အကယ်၍ မရှိပါက၎င်းသည်ကျွန်ုပ်တောင်းဆိုသောစာလုံးအရေအတွက်ကိုသာဖြတ်တောက်လိမ့်မည်။ နေရာလွတ်ရှိလျှင်၊ ကျွန်ုပ်သည်ကျွန်ုပ်၏အကြောင်းအရာကိုအာကာသထဲတွင်လျောက်ပတ်စွာဖြတ်ပစ်လိမ့်မည်။
ဤသည်မှာအက္ခရာအများဆုံးအရေအတွက်ပေါင်းစပ်အသုံးပြုခြင်းနှင့်စာလုံးကိုဖြတ်တောက်ခြင်းကိုအကောင်းဆုံးနည်းလမ်းဖြစ်သည်။ မင်းကြိုက်လားမျှော်လင့်ပါတယ်
ပြီးတော့ ASP.NET function တစ်ခုခုလုပ်လို့ရလားဆိုတာငါရှာမယ်သေချာတယ်။ အဲဒါကိုငါရှာမရဘူး။
Doug, in C# you can use the String.LastIndexOf method to do what strrpos does in PHP.
I knew that would happen! 🙂
Thanks, Abhijit!
Excellent! Just what I was looking for. Thanks.
If $content is initially SHORTER than $maxchars the code as written will still look right to left for a space and cut out the last word. You can either concatenate a space at the end of $content, or do an if (strlen()…)
This seemed to work as a function (addressing the previous comment):
function showexcerpt($content, $maxchars) {
if (strlen($content) > $maxchars) {
$content= substr($content, 0, $maxchars);
$pos = strrpos($content, " ");
if ($pos>0) {
$content = substr($content, 0, $pos);
}
return $content . "…";
} သည်အခြား {
ပြန်လာ $ အကြောင်းအရာ;
}
}
What if our final character is a punctuation character like a full-stop, exclamation mark or question mark? Unfortunately, this code will wipe the entire word preceding said punctuation character.
I think you’d be better off writing something a little more robust.
Such a good idea!