Remove quotes from start and end of string in PHP

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

    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

提交回复
热议问题