Golang:逃避单引号

问题描述 投票:8回答:3

有没有办法逃避单引号?

下列:

str := "I'm Bob, and I'm 25."
str = strings.Replace(str, "'", "\'", -1)

给出错误:未知的转义序列:'

我想成为

"I\'m Bob, and I\'m 25."
go escaping backslash quote
3个回答
22
投票

你还需要在strings.Replace中转义斜杠。

str := "I'm Bob, and I'm 25."
str = strings.Replace(str, "'", "\\'", -1)

https://play.golang.org/p/mZaaNU3FHw


10
投票

+到@KeylorSanchez回答:你可以在后面的方法中包换替换字符串:

strings.Replace(str, "'", `\'`, -1)

-1
投票
// addslashes()
func Addslashes(str string) string {
    var buf bytes.Buffer
    for _, char := range str {
        switch char {
        case '\'':
            buf.WriteRune('\\')
        }
        buf.WriteRune(char)
    }
    return buf.String()
}

如果你想逃避单/双引号或反弹,你可以参考https://github.com/syyongx/php2go

© www.soinside.com 2019 - 2024. All rights reserved.