github.com/wangyougui/gf/v2@v2.6.5/text/gstr/gstr_slashes.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gstr 8 9 import ( 10 "bytes" 11 12 "github.com/wangyougui/gf/v2/internal/utils" 13 ) 14 15 // AddSlashes quotes with slashes `\` for chars: '"\. 16 func AddSlashes(str string) string { 17 var buf bytes.Buffer 18 for _, char := range str { 19 switch char { 20 case '\'', '"', '\\': 21 buf.WriteRune('\\') 22 } 23 buf.WriteRune(char) 24 } 25 return buf.String() 26 } 27 28 // StripSlashes un-quotes a quoted string by AddSlashes. 29 func StripSlashes(str string) string { 30 return utils.StripSlashes(str) 31 } 32 33 // QuoteMeta returns a version of `str` with a backslash character (`\`). 34 // If custom chars `chars` not given, it uses default chars: .\+*?[^]($) 35 func QuoteMeta(str string, chars ...string) string { 36 var buf bytes.Buffer 37 for _, char := range str { 38 if len(chars) > 0 { 39 for _, c := range chars[0] { 40 if c == char { 41 buf.WriteRune('\\') 42 break 43 } 44 } 45 } else { 46 switch char { 47 case '.', '+', '\\', '(', '$', ')', '[', '^', ']', '*', '?': 48 buf.WriteRune('\\') 49 } 50 } 51 buf.WriteRune(char) 52 } 53 return buf.String() 54 }