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

lambar html

Idan kuna aiki tare da PHP kuma kuna son kawai 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 kirtani. Dole ne in rubuta aiki don yin wannan a cikin ASP da ASP.NET wanda ke motsawa 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, strpos.

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.