gstr_replace.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. "github.com/gogf/gf/internal/utils"
  9. "strings"
  10. )
  11. // Replace returns a copy of the string `origin`
  12. // in which string `search` replaced by `replace` case-sensitively.
  13. func Replace(origin, search, replace string, count ...int) string {
  14. n := -1
  15. if len(count) > 0 {
  16. n = count[0]
  17. }
  18. return strings.Replace(origin, search, replace, n)
  19. }
  20. // ReplaceI returns a copy of the string `origin`
  21. // in which string `search` replaced by `replace` case-insensitively.
  22. func ReplaceI(origin, search, replace string, count ...int) string {
  23. n := -1
  24. if len(count) > 0 {
  25. n = count[0]
  26. }
  27. if n == 0 {
  28. return origin
  29. }
  30. var (
  31. length = len(search)
  32. searchLower = strings.ToLower(search)
  33. )
  34. for {
  35. originLower := strings.ToLower(origin)
  36. if pos := strings.Index(originLower, searchLower); pos != -1 {
  37. origin = origin[:pos] + replace + origin[pos+length:]
  38. if n--; n == 0 {
  39. break
  40. }
  41. } else {
  42. break
  43. }
  44. }
  45. return origin
  46. }
  47. // ReplaceByArray returns a copy of `origin`,
  48. // which is replaced by a slice in order, case-sensitively.
  49. func ReplaceByArray(origin string, array []string) string {
  50. for i := 0; i < len(array); i += 2 {
  51. if i+1 >= len(array) {
  52. break
  53. }
  54. origin = Replace(origin, array[i], array[i+1])
  55. }
  56. return origin
  57. }
  58. // ReplaceIByArray returns a copy of `origin`,
  59. // which is replaced by a slice in order, case-insensitively.
  60. func ReplaceIByArray(origin string, array []string) string {
  61. for i := 0; i < len(array); i += 2 {
  62. if i+1 >= len(array) {
  63. break
  64. }
  65. origin = ReplaceI(origin, array[i], array[i+1])
  66. }
  67. return origin
  68. }
  69. // ReplaceByMap returns a copy of `origin`,
  70. // which is replaced by a map in unordered way, case-sensitively.
  71. func ReplaceByMap(origin string, replaces map[string]string) string {
  72. return utils.ReplaceByMap(origin, replaces)
  73. }
  74. // ReplaceIByMap returns a copy of `origin`,
  75. // which is replaced by a map in unordered way, case-insensitively.
  76. func ReplaceIByMap(origin string, replaces map[string]string) string {
  77. for k, v := range replaces {
  78. origin = ReplaceI(origin, k, v)
  79. }
  80. return origin
  81. }