PHP: Yanke abin da kuka zana a kalmar ta amfani da strrpos

lambar html

Idan kuna aiki tare da PHP kuma kuna so kawai ku nuna wani yanki daga rubutun asalin ku kuma yanke shi da wasu haruffa, abubuwan da kuka zana na iya zama marasa kyau idan anyi tsakiyar layi. Dole ne in rubuta aiki don yin wannan a cikin ASP da ASP.NET wanda ke motsa jiki daga yanayin ƙarshe don nemo sararin ƙarshe kuma yanke shi a can. Nau'in m da kuma ɗan overkill. Kuna iya ganin wannan a aikace akan gidana Page inda kawai na samar da haruffa 500 na farko.

Na shirya tsaf don haɓaka wannan aiki tare da PHP a yau amma na sami (kamar yadda aka saba) cewa PHP yana da aiki wanda yake aikata shi tuni, strrpos.

Tsohuwar lambar za ta ɗauki abun ($ abun ciki) daga farkon haruffa zuwa iyakar adadin haruffan da kuke so ($ maxchars):

$ abun ciki = substr ($ abun ciki, 0, $ maxchars); amsa kuwwa $ abun ciki;

Sabuwar lambar:

$ abun ciki = substr ($ abun ciki, 0, $ maxchars); $ pos = strrpos ($ abun ciki, ""); idan ($ pos> 0) {$ abun ciki = substr ($ abun ciki, 0, $ pos); } amsa kuwwa $ abun ciki;

Don haka sabuwar lambar ta fara yanke abun ciki a iyakar halin da kuke nema. Koyaya, mataki na gaba shine neman sararin ƙarshe ("") a cikin abun ciki. $ pos zai tashi kasancewar wannan matsayin. Yanzu, Ina kawai tabbatar da cewa a zahiri akwai sarari a cikin abubuwan ta hanyar tambayar idan $ pos> 0. Idan babu, zai iya yanke abun cikin adadin haruffan da na nema. Idan akwai wani sarari, zai yanke abun cikina da kyau.

Wannan hanya ce mai kyau ta amfani da haɗin iyakar adadin haruffa da yanke shi a kalmar. Fata kuna so!

Kuma na tabbata zan gano idan akwai aikin ASP.NET da ke yin wannan… Ban sami guda ba.

7 Comments

  1. 1
  2. 2
  3. 3
  4. 4

    Idan da farko abun cikin $ SHORTER ne fiye da $ maxchars lambar kamar yadda aka rubuta zasuyi duba dama zuwa hagu don sarari kuma yanke kalma ta ƙarshe. Kuna iya haɗa sarari a ƙarshen $ abun ciki, ko yin wani idan (strlen ()…)

  5. 5

    Wannan yana da alama aiki azaman aiki (magance maganganun baya):

    aiki showexcerpt ($ abun ciki, $ maxchars) {

    idan (strlen ($ abun ciki)> $ maxchars) {

    $ abun ciki = substr ($ abun ciki, 0, $ maxchars);
    $ pos = strrpos ($ abun ciki, "");

    idan ($ pos> 0) {
    $ abun ciki = substr ($ abun ciki, 0, $ pos);
    }

    maida $ abun ciki. "…";

    } da {

    dawo da abun ciki na $;

    }

    }

  6. 6

    Me zai faru idan halin mu na karshe dabi'ar rubutu ne kamar cikar gaba, alamar motsin rai ko alamar tambaya? Abun takaici, wannan lambar zata goge dukkan kalmar da ta gabata da harafin rubutu.  

    Ina tsammanin za ku fi dacewa da rubuta wani abu kaɗan da ƙarfi.

  7. 7

Me kuke tunani?

Wannan shafin yana amfani da Akismet don rage spam. Koyi yadda aka sarrafa bayanan bayaninka.