/
gstr_replace.go
94 lines (85 loc) · 2.39 KB
/
gstr_replace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gstr
import (
"strings"
"github.com/gogf/gf/v2/internal/utils"
)
// Replace returns a copy of the string `origin`
// in which string `search` replaced by `replace` case-sensitively.
func Replace(origin, search, replace string, count ...int) string {
n := -1
if len(count) > 0 {
n = count[0]
}
return strings.Replace(origin, search, replace, n)
}
// ReplaceI returns a copy of the string `origin`
// in which string `search` replaced by `replace` case-insensitively.
func ReplaceI(origin, search, replace string, count ...int) string {
n := -1
if len(count) > 0 {
n = count[0]
}
if n == 0 {
return origin
}
var (
searchLength = len(search)
replaceLength = len(replace)
searchLower = strings.ToLower(search)
originLower string
pos int
)
for {
originLower = strings.ToLower(origin)
if pos = Pos(originLower, searchLower, pos); pos != -1 {
origin = origin[:pos] + replace + origin[pos+searchLength:]
pos += replaceLength
if n--; n == 0 {
break
}
} else {
break
}
}
return origin
}
// ReplaceByArray returns a copy of `origin`,
// which is replaced by a slice in order, case-sensitively.
func ReplaceByArray(origin string, array []string) string {
for i := 0; i < len(array); i += 2 {
if i+1 >= len(array) {
break
}
origin = Replace(origin, array[i], array[i+1])
}
return origin
}
// ReplaceIByArray returns a copy of `origin`,
// which is replaced by a slice in order, case-insensitively.
func ReplaceIByArray(origin string, array []string) string {
for i := 0; i < len(array); i += 2 {
if i+1 >= len(array) {
break
}
origin = ReplaceI(origin, array[i], array[i+1])
}
return origin
}
// ReplaceByMap returns a copy of `origin`,
// which is replaced by a map in unordered way, case-sensitively.
func ReplaceByMap(origin string, replaces map[string]string) string {
return utils.ReplaceByMap(origin, replaces)
}
// ReplaceIByMap returns a copy of `origin`,
// which is replaced by a map in unordered way, case-insensitively.
func ReplaceIByMap(origin string, replaces map[string]string) string {
for k, v := range replaces {
origin = ReplaceI(origin, k, v)
}
return origin
}