php - Can't remove \ufeff from a string - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

3) I open the file with fopen() and read the file with fgetcsv() . The first column it always have the \ufeff char. I know that is called UTF-8 ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Can'tremove\ufefffromastring AskQuestion Asked 3years,9monthsago Modified 11monthsago Viewed 12ktimes 7 Theappbasicallyworkslikethis: 1)TheuseruploadsaCSVfile. 2)ThefileiscatchedbyPHPviaPOST. 3)Iopenthefilewithfopen()andreadthefilewithfgetcsv(). Thefirstcolumnitalwayshavethe\ufeffchar.IknowthatiscalledUTF-8BOM,andit'sgeneratedbyMicrosoftExcel.But,whenIwanttoremovethat,Ican't. I'vetried:str_replace('\ufeff','',$columns[0]); phpcharacter-encoding Share Improvethisquestion Follow askedJan11,2019at10:52 AngelLuisAngelLuis 40522goldbadges55silverbadges1717bronzebadges 7 '\ufeff'isnotavalidCescape,andwouldn'tworkinsinglequotesanyway. – mario Jan11,2019at10:57 0xFEFFistheUTF-16big-endianbyteordermarker(reference).Itdoesn'tmakemuchsensetojuststripit...:-? – ÁlvaroGonzález Jan11,2019at10:59 @ÁlvaroGonzálezIdon'tunderstandatallwhyIcan'tstripthat. – AngelLuis Jan11,2019at11:03 1 Well...IfyourapplicationusesUTF-8(asyourquestionimplies)andyoureadaUTF-16fileassumingit'sUTF-8you'lleitherendupwithcorruptdata(ifyoumergeUTF-8charswithUTF-16chars)oryou'llhaveacorrectUTF-16streamthatcannotbedecodedbecauseitmissesthebyte-orderinformation. – ÁlvaroGonzález Jan11,2019at12:04 Thiswasclosedasduplicatebutthelinkedquestiondidn'tapplyherebecausewe'retalkingabouta(mandatory)UTF-16BOM(theUTF-8BOMis0xEFBBBFandit'soptional. – ÁlvaroGonzález Jan11,2019at12:07  |  Show2morecomments 4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 14 $columns[0]=preg_replace('/[\x00-\x1F\x80-\xFF]/','',$columns[0]); Theabovecodehelpsyouremovehiddencharactersthatexistinyourdocument,justliketheoneyoumentioned. Share Improvethisanswer Follow answeredJan11,2019at10:58 pr1nc3pr1nc3 7,63233goldbadges2121silverbadges3535bronzebadges 9 PDofHowdoIremovefromthebeginningofafile?.Andthisremovesquiteabitmore. – mario Jan11,2019at11:00 Itworks,thankyou.CanIknowwhatIremovingexactlywiththatregex? – AngelLuis Jan11,2019at11:02 Youareremovingspecialcharacters. – pr1nc3 Jan11,2019at11:03 @pr1nc3IneachpageIseedifferentregexfordothesametask. – AngelLuis Jan11,2019at11:05 1 Beaware,thisalsoremoveaccents – Cyprien Jan9at19:19  |  Show4morecomments 2 $result=trim($result,"\xEF\xBB\xBF"); Thisisthesimplestwaytosolveit. Share Improvethisanswer Follow answeredAug19,2021at3:00 TerryLinTerryLin 2,3331717silverbadges1919bronzebadges 2 Whilethiscodemaysolvethequestion,includinganexplanationofhowandwhythissolvestheproblemwouldreallyhelptoimprovethequalityofyourpost,andprobablyresultinmoreup-votes.Rememberthatyouareansweringthequestionforreadersinthefuture,notjustthepersonaskingnow.Pleaseedityouranswertoaddexplanationsandgiveanindicationofwhatlimitationsandassumptionsapply. – Yunnosch Oct25,2021at9:31 Thankyou!thisissolutioniwaslookingfor!@Yunnoschohplease... – HelpNeeder Sep1at2:35 Addacomment  |  1 $headings=array(); $handle=fopen($_FILES["contacts_file"]["tmp_name"],"r"); $heading_data=fgetcsv($handle); foreach($heading_dataas$heading){ //Removeanyinvalidorhiddencharacters $heading=preg_replace('/[\x00-\x1F\x80-\xFF]/','',$heading); array_push($headings,$heading); } Share Improvethisanswer Follow answeredMay7,2020at11:21 jamesacejamesace 2,0132323silverbadges1313bronzebadges 2 Whilethiscodemaysolvethequestion,includinganexplanationofhowandwhythissolvestheproblemwouldreallyhelptoimprovethequalityofyourpost,andprobablyresultinmoreup-votes.Rememberthatyouareansweringthequestionforreadersinthefuture,notjustthepersonaskingnow.Pleaseedityouranswertoaddexplanationsandgiveanindicationofwhatlimitationsandassumptionsapply. – Yunnosch Oct25,2021at9:32 Thiswashelpfultome,duetothecontext-I'mprocessingtheCSVfileuploadinCodeigniterandIneededawaytostriptheBOMfromthefirstlineofthefile. – WojCup Jan27at14:06 Addacomment  |  0 $columns[0]=preg_replace('/\xEF\xBB\xBF/','',$columns[0]); or $columns[0]=trim($columns[0],"\xEF\xBB\xBF"); Share Improvethisanswer Follow answeredOct25,2021at9:20 CarlosArranzCarlosArranz 1 2 1 WelcometoStackOverflow!Whilethiscodemaysolvethequestion,includinganexplanationofhowandwhythissolvestheproblemwouldreallyhelptoimprovethequalityofyourpost,andprobablyresultinmoreup-votes.Rememberthatyouareansweringthequestionforreadersinthefuture,notjustthepersonaskingnow.Pleaseedityouranswertoaddexplanationsandgiveanindicationofwhatlimitationsandassumptionsapply. – Yunnosch Oct25,2021at9:29 Doingsopleaseespeciallyelaboratethefunctionaldifferencetothetwoexistinganswersstackoverflow.com/a/68841510/7733418andstackoverflow.com/a/54145162/7733418Becausethispostdoesnotseemtoaddanything. – Yunnosch Oct25,2021at9:30 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedphpcharacter-encodingoraskyourownquestion. TheOverflowBlog HowtoearnamillionreputationonStackOverflow:beofservicetoothers Therightwaytojobhop(Ep.495) FeaturedonMeta BookmarkshaveevolvedintoSaves Inboximprovements:markingnotificationsasread/unread,andafiltered... Revieweroverboard!Orarequesttoimprovetheonboardingguidancefornew... CollectivesUpdate:RecognizedMembers,Articles,andGitLab Shouldweburninatethe[script]tag? Visitchat Linked 70 HowtoremovemultipleUTF-8BOMsequences Related 2944 DeletinganelementfromanarrayinPHP 2718 HowdoIgetaYouTubevideothumbnailfromtheYouTubeAPI? 166 HowdoIremovefromthebeginningofafile? 976 Removeemptyarrayelements 214 HowcanIoutputaUTF-8CSVinPHPthatExcelwillreadproperly? 2657 HowdoIcheckifastringcontainsaspecificword? 2 PHP-CSVtoMySQLtofrontend,andbacktoCSV,bestencoding/stringfunctionpractices? 812 Removetrailingdelimitingcharacterfromadelimitedstring 1347 BestwaytoconvertstringtobytesinPython3? 4 HowtoescapecommaforCSV,fgetcsv()issue HotNetworkQuestions circuitikz:Addingarrowheadtotapofvariableinductance? Applying5Vto3.3Voutputpins Canaphotonturnaprotonintoaneutron? IsdocumentingabigprojectwithUMLDiagramsneeded,goodtohaveorevennotpossible? IfthedrowshadowbladeusesShadowSwordasarangedattack,doesitthrowasword(thatitthenhastoretrievebeforeusingitagain)? Whataretheargumentsforrevengeandretribution? PacifistethosblockingmyprogressinStellaris Howtodecompose8x8UnitaryMatrixintotensorproductofthreephasedgate? Whoorwhatis"Nampat"inthechantoftheOrcsintheRingsofPower? DoestheDemocraticPartyofficiallysupportrepealingtheSecondAmendment? Whatisthebestwaytocalculatetruepasswordentropyforhumancreatedpasswords? Howtoelegantlyimplementthisoneusefulobject-orientedfeatureinMathematica? ElectronicCircuitsforSafeInitiationofPyrotechnics? 9dotsthatare3by3,continuethepattern Isitcorrecttochangetheverbto"being"in"Despitenoonewashurtinthisincident…"? Idon'tunderstandif"per"meaningexactamountforeachunitordoesitmean"onaverage" Howdoyoucalculatethetimeuntilthesteady-stateofadrug? Howdoparty-listsystemsaccommodateindependentcandidates? WherewasthisneonsignofadragondisplayedinLosAngelesinthe1990s?Isitstilltherenow? DidMS-DOSeverdropabilitytosupportnon-IBMPCcompatiblemachines? Areopeningandclosingstatementspartoftherecord? WhatisthedifferencebetweenGlidepathversusGlideslope? Unsurewhatthesewatersoftenerdialsarefor Realitycheck:PolarCO2lakescoexistingwithanequatorialH2Oocean morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-php Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?