Vấn đề là thay thế đơn giản làm sạch mỗi ký tự trích dẫn, ngay cả khi đã thoát (tăng gấp đôi). Dưới đây là các chức năng tôi đã tạo để sử dụng:
- chỉ xóa một báo giá mồ côi.
- một mà thoát chúng
Tôi cũng làm cho họ chung để quản lý các nhân vật khác, với tham số charToReplace optionnal $
#Replaces single occurences of characters in a string.
#Default is to replace single quotes
Function RemoveNonEscapedChar {
param(
[Parameter(Mandatory = $true)][String] $param,
[Parameter(Mandatory = $false)][String] $charToReplace
)
if ($charToReplace -eq '') {
$charToReplace = "'"
}
$cleanedString = ""
$index = 0
$length = $param.length
for ($index = 0; $index -lt $length; $index++) {
$char = $param[$index]
if ($char -eq $charToReplace) {
if ($index +1 -lt $length -and $param[$index + 1] -eq $charToReplace) {
$cleanedString += "$charToReplace$charToReplace"
++$index ## /!\ Manual increment of our loop counter to skip next char /!\
}
continue
}
$cleanedString += $char
}
return $cleanedString
}
#A few test cases :
RemoveNonEscapedChar("'st''r'''i''ng'") #Echoes st''r''i''ng
RemoveNonEscapedChar("""st""""r""""""i""""ng""") -charToReplace '"' #Echoes st""r""i""ng
RemoveNonEscapedChar("'st''r'''i''ng'") -charToReplace 'r' #Echoes 'st'''''i''ng'
#Escapes single occurences of characters in a string. Double occurences are not escaped. e.g. ''' will become '''', NOT ''''''.
#Default is to replace single quotes
Function EscapeChar {
param(
[Parameter(Mandatory = $true)][String] $param,
[Parameter(Mandatory = $false)][String] $charToEscape
)
if ($charToEscape -eq '') {
$charToEscape = "'"
}
$cleanedString = ""
$index = 0
$length = $param.length
for ($index = 0; $index -lt $length; $index++) {
$char = $param[$index]
if ($char -eq $charToEscape) {
if ($index +1 -lt $length -and $param[$index + 1] -eq $charToEscape) {
++$index ## /!\ Manual increment of our loop counter to skip next char /!\
}
$cleanedString += "$charToEscape$charToEscape"
continue
}
$cleanedString += $char
}
return $cleanedString
}
#A few test cases :
EscapeChar("'st''r'''i''ng'") #Echoes ''st''r''''i''ng''
EscapeChar("""st""""r""""""i""""ng""") -charToEscape '"' #Echoes ""st""r""""i""ng""
EscapeChar("'st''r'''i''ng'") -charToEscape 'r' #Echoes 'st''rr'''i''ng'
Great điểm. Sẽ xem xét điều đó – Pat