-
Notifications
You must be signed in to change notification settings - Fork 62
/
string.go
50 lines (45 loc) · 1000 Bytes
/
string.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
package yiigo
import "strings"
// AddSlashes 在字符串的每个引号前添加反斜杠
func AddSlashes(s string) string {
var builder strings.Builder
for _, ch := range s {
if ch == '\'' || ch == '"' || ch == '\\' {
builder.WriteRune('\\')
}
builder.WriteRune(ch)
}
return builder.String()
}
// StripSlashes 删除字符串中的反斜杠
func StripSlashes(s string) string {
l, skip := len(s), false
var builder strings.Builder
for i, ch := range s {
if skip {
builder.WriteRune(ch)
skip = false
continue
}
if ch == '\\' {
if i+1 < l && s[i+1] == '\\' {
skip = true
}
continue
}
builder.WriteRune(ch)
}
return builder.String()
}
// QuoteMeta 在字符串预定义的字符前添加反斜杠
func QuoteMeta(s string) string {
var builder strings.Builder
for _, ch := range s {
switch ch {
case '.', '+', '\\', '(', '$', ')', '[', '^', ']', '*', '?':
builder.WriteRune('\\')
}
builder.WriteRune(ch)
}
return builder.String()
}