Php – Remove quotes from start and end of string in PHP

phpstring

I have strings like these:

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

I need to get rid of " (double-quotes) in end and start, if these exist, but if there is this kind of character inside String then it should be left there. Example:

"my " value1" => my " value1

How can I do this in PHP – is there function for this or do I have to code it myself?

Best Solution

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.