newbie
newbie

Reputation: 24625

Remove quotes from start and end of string in PHP

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?

Upvotes: 50

Views: 108954

Answers (8)

Steve Chambers
Steve Chambers

Reputation: 39394

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/8

Upvotes: 23

Your Common Sense
Your Common Sense

Reputation: 157828

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.

Upvotes: 116

Mark Bradley
Mark Bradley

Reputation: 510

This is an old post, but just to cater for multibyte strings, there are at least two possible routes one can follow. I am assuming that the quote stripping is being done because the quote is being considered like a program / INI variable and thus is EITHER "something" or 'somethingelse' but NOT "mixed quotes'. Also, ANYTHING between the matched quotes is to be retained intact.
Route 1 - using a Regex

function sq_re($i) {
    return preg_replace( '#^(\'|")(.*)\1$#isu', '$2', $i );
}

This uses \1 to match the same type quote that matched at the beginning. the u modifier, makes it UTF8 capable (okay, not fully multibyte supporting)


Route 2 - using mb_* functions

function sq($i) {
    $f = mb_substr($i, 0, 1);
    $l = mb_substr($i, -1);
    if (($f == $l) && (($f == '"') || ($f == '\'')) ) $i = mb_substr($i, 1, mb_strlen( $i ) - 2);
    return $i;
}

Upvotes: 1

Melo Waste
Melo Waste

Reputation: 161

If you like performance over clarity this is the way:

// Remove double quotes at beginning and/or end of output
$len=strlen($output);
if($output[0]==='"') $iniidx=1; else $iniidx=0;
if($output[$len-1]==='"') $endidx=-1; else $endidx=$len-1;
if($iniidx==1 || $endidx==-1) $output=substr($output,$iniidx,$endidx);

The comment helps with clarity... brackets in an array-like usage on strings is possible and demands less processing effort than equivalent methods, too bad there isnt a length variable or a last char index

Upvotes: 0

Scott Horsley HRabbit
Scott Horsley HRabbit

Reputation: 41

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.

Upvotes: 4

sakhunzai
sakhunzai

Reputation: 14470

How about regex

//$singleQuotedString="'Hello this 'someword' and \"somewrod\" stas's SO";
//$singleQuotedString="Hello this 'someword' and \"somewrod\" stas's SO'";
$singleQuotedString="'Hello this 'someword' and \"somewrod\" stas's SO'";

$quotesFreeString=preg_replace('/^\'?(.*?(?=\'?$))\'?$/','$1' ,$singleQuotedString);

Output

Hello this 'someword' and "somewrod" stas's SO   

Upvotes: 0

user783322
user783322

Reputation: 481

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);

Upvotes: 9

Purpletoucan
Purpletoucan

Reputation: 6572

You need to use regular expressions, look at:-

http://php.net/manual/en/function.preg-replace.php

Or you could, in this instance, use substr to check if the first and then the last character of the string is a quote mark, if it is, truncate the string.

http://php.net/manual/en/function.substr.php

Upvotes: 0

Related Questions