Remove quotes from start and end of string in PHP

I had a similar need and wrote a function that will remove leading and trailing single or double quotes from a string:

/**
 * Remove the first and last quote from a quoted string of text
 *
 * @param mixed $text
 */
function stripQuotes($text) {
  return preg_replace('/^(\'(.*)\'|"(.*)")$/', '$2$3', $text);
} 

This will produce the outputs listed below:

Input text         Output text
--------------------------------
No quotes       => No quotes
"Double quoted" => Double quoted
'Single quoted' => Single quoted
"One of each'   => "One of each'
"Multi""quotes" => Multi""quotes
'"'"@";'"*&^*'' => "'"@";'"*&^*'

Regex demo (showing what is being matched/captured): https://regex101.com/r/3otW7H/1


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.


As much as this thread should have been killed long ago, I couldn't help but respond with what I would call the simplest answer of all. I noticed this thread re-emerging on the 17th so I don't feel quite as bad about this. :)

Using samples as provided by Steve Chambers;

echo preg_replace('/(^[\"\']|[\"\']$)/', '', $input);

Output below;

Input text         Output text
--------------------------------
No quotes       => No quotes
"Double quoted" => Double quoted
'Single quoted' => Single quoted
"One of each'   => One of each
"Multi""quotes" => Multi""quotes
'"'"@";'"*&^*'' => "'"@";'"*&^*'

This only ever removes the first and last quote, it doesn't repeat to remove extra content and doesn't care about matching ends.


trim will remove all instances of the char from the start and end if it matches the pattern you provide, so:

$myValue => '"Hi"""""';
$myValue=trim($myValue, '"');

Will become:

$myValue => 'Hi'.

Here's a way to only remove the first and last char if they match:

$output=stripslashes(trim($myValue));

// if the first char is a " then remove it
if(strpos($output,'"')===0)$output=substr($output,1,(strlen($output)-1));

// if the last char is a " then remove it
if(strripos($output,'"')===(strlen($output)-1))$output=substr($output,0,-1);

Tags:

Php

String