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