从PHP中的字符串的开头和结尾删除引号

new*_*bie 39 php string

我有这样的字符串:

"my value1" => my value1
"my Value2" => my Value2
myvalue3 => myvalue3 
Run Code Online (Sandbox Code Playgroud)

我需要"在最后删除(双引号)并开始,如果这些存在,但如果在String内有这种字符,那么它应该留在那里.例:

"my " value1" => my " value1
Run Code Online (Sandbox Code Playgroud)

我如何在PHP中执行此操作 - 是否有此功能或我是否必须自己编写代码?

You*_*nse 89

trim($string,'"');
Run Code Online (Sandbox Code Playgroud)

这是源头

  • 如果第二个字符也是'“'或倒数第二个字符,则该字符也将被删除。如果这些字符有效,则修剪下降。它取决于实际数据。请参见user783322的回答。 (2认同)
  • 这不应该是公认的答案。如果引号是字符串的一部分怎么办?`"this is double-quote -> ""` 将输出 `this is double-quote -> ` 这意味着您错过了字符串的一个组成部分。 (2认同)

Ste*_*ers 14

我有类似的需求,并编写了一个函数,将从字符串中删除前导和尾随的单引号或双引号:

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

这将产生下列输出:

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
'"'"@";'"*&^*'' => "'"@";'"*&^*'
Run Code Online (Sandbox Code Playgroud)


use*_*322 7

trim 如果它与您提供的模式匹配,将从开头和结尾删除所有char实例,因此:

$myValue => '"Hi"""""';
$myValue=trim($myValue, '"');
Run Code Online (Sandbox Code Playgroud)

会变成:

$myValue => 'Hi'.
Run Code Online (Sandbox Code Playgroud)

这是一种只有在匹配时才删除第一个和最后一个字符的方法:

$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);
Run Code Online (Sandbox Code Playgroud)