Remove quotes from start and end of string in PHP

前端 未结 8 1855
醉酒成梦
醉酒成梦 2020-12-29 01:34

I have strings like these:

\"my value1\" => my value1
\"my Value2\" => my Value2
myvalue3 => myvalue3 
         


        
8条回答
  •  爱一瞬间的悲伤
    2020-12-29 02:13

    The literal answer would be

    trim($string,'"'); // double quotes
    trim($string,'\'"'); // any combination of ' and "
    

    It will remove all leading and trailing quotes from a string.

    If you need to remove strictly the first and the last quote in case they exist, then it could be a regular expression like this

    preg_replace('~^"?(.*?)"?$~', '$1', $string); // double quotes
    preg_replace('~^[\'"]?(.*?)[\'"]?$~', '$1', $string); // either ' or " whichever is found
    

    If you need to remove only in case the leading and trailing quote are strictly paired, then use the function from Steve Chambers' answer

    However, if your goal is to read a value from a CSV file, fgetcsv is the only correct option. It will take care of all the edge cases, stripping the value enclosures as well.

提交回复
热议问题