gstr_slashes.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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/gogf/gf.
  6. package gstr
  7. import (
  8. "bytes"
  9. "github.com/gogf/gf/v2/internal/utils"
  10. )
  11. // AddSlashes quotes with slashes `\` for chars: '"\.
  12. func AddSlashes(str string) string {
  13. var buf bytes.Buffer
  14. for _, char := range str {
  15. switch char {
  16. case '\'', '"', '\\':
  17. buf.WriteRune('\\')
  18. }
  19. buf.WriteRune(char)
  20. }
  21. return buf.String()
  22. }
  23. // StripSlashes un-quotes a quoted string by AddSlashes.
  24. func StripSlashes(str string) string {
  25. return utils.StripSlashes(str)
  26. }
  27. // QuoteMeta returns a version of `str` with a backslash character (`\`).
  28. // If custom chars `chars` not given, it uses default chars: .\+*?[^]($)
  29. func QuoteMeta(str string, chars ...string) string {
  30. var buf bytes.Buffer
  31. for _, char := range str {
  32. if len(chars) > 0 {
  33. for _, c := range chars[0] {
  34. if c == char {
  35. buf.WriteRune('\\')
  36. break
  37. }
  38. }
  39. } else {
  40. switch char {
  41. case '.', '+', '\\', '(', '$', ')', '[', '^', ']', '*', '?':
  42. buf.WriteRune('\\')
  43. }
  44. }
  45. buf.WriteRune(char)
  46. }
  47. return buf.String()
  48. }