Remove quotes from start and end of string in PHP

前端 未结 8 1815
醉酒成梦
醉酒成梦 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:19

    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

    0 讨论(0)
  • 2020-12-29 02:20

    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;
    }
    
    0 讨论(0)
提交回复
热议问题