[英]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
我可以使用substr
和trim
邏輯輕松地做到這一點,但是我很想使用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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.