删除字符串开头/结尾的单/双引号,仅当它们将字符串括起来时


Removing single/double quotes from beginning/end of string, only if they enclose it

我试图在PHP中使用正则表达式从字符串的开始和结束处剥离单引号或双引号,但我们只想删除它们,如果它们存在于字符串的每个末尾。这样,用作度量的引号就不会丢失。

例如:

"3' 7"" - would remove quotes
3' 7" - would not remove

我可以很容易地用substrtrim逻辑做到这一点,但我喜欢用regex一次做到这一切。

替换单引号或双引号,并确保它们必须匹配:

preg_replace('/^([''"])(.*)''1$/', '''2', $value);
preg_replace('/^"(.*)"$/', '$1', '"3' 7""');
preg_replace('/^"(.*)"$/', '$1', '"3'' 7""');

正则表达式的方法是捕获引号,然后稍后再引用它。引号内的内容也应该被捕获,以便它可以用作替换:

$x = array('3'' 7"', '''3'' 7"''', '"3'' 7""');
foreach ($x as $y)
    echo preg_replace('/^(["''])(.*)''1$/', '$2', $y), '<br>';
die;

现在,正则表达式的方式是可以的,但是"手动"操作可能更容易理解,并在将来维护:

function remove_quotes($string)
{
    $length = strlen($string);
    if ($length > 2)
    {
        foreach (array('''', '"') as $quote)
        {
            if ($string[0] === $quote && $string[$length-1] === $quote)
            {
                $string = substr($string, 1, -1);
                break;
            }
        }
    }
    return $string;
}
$x = array('3'' 7"', '''3'' 7"''', '"3'' 7""');
foreach ($x as $y)
    echo remove_quotes($y), '<br>';
die;