当前位置:在线工具>转换相关>字符串转义 / 字符串反转义
手机访问
字符串转义 / 字符串反转义
字符串转义工具的说明
函数使用反斜线引用字符串。包括的这些字符是:
  1. 单引号(')
  2. 双引号(“)
  3. 反斜杠(\)
  4. NUL(NUL字节)
字符串转义、字符串反转义的例子
Example PHP

示例 #1 PHP 7.1+ addslashes 使用反斜线引用字符串

<?php
$str = "Is your name O'Reilly?";
echo addslashes($str);

输出结果:Is your name O\'Reilly?

示例 #2 PHP 7.1+ stripslashes 反引用一个引用字符串

<?php
$str = "Is your name O\'Reilly?";
echo stripslashes($str);

输出的结果:Is your name O'Reilly?

Example Go

示例 #1 Go 1.26 模拟 PHP 函数 addslashes 例子

package main

import (
    "strings"
)

// 转义:' " \ 和 NULL 字符
// 函数名称首字母大写允许包外调用, 这是 Go 语言约定
func AddSlashes(str string) string {
    var builder strings.Builder
    builder.Grow(len(str) + 10) // 预分配一些空间,提升性能

    for _, ch := range str {
        switch ch {
        case '\'':
            builder.WriteString("\\'")
        case '"':
            builder.WriteString("\\\"")
        case '\\':
            builder.WriteString("\\\\")
        case '\x00': // NULL 字符
            builder.WriteString("\\0")
        default:
            builder.WriteRune(ch)
        }
    }
    return builder.String()
}

func main() {
    input := "Is your name O'Reilly?"
    println(AddSlashes(input))
}

输出的结果:Is your name O\'Reilly?

示例 #2 Go 1.26 模拟 PHP 函数 stripslashes

package main

import (
    "strings"
)

// 还原被 addslashes 转义的字符
func StripSlashes(str string) string {
    var builder strings.Builder
    builder.Grow(len(str))

    runes := []rune(str)
    for i := 0; i < len(runes); i++ {
        if runes[i] == '\\' && i+1 < len(runes) {
            // 处理转义序列
            next := runes[i+1]
            switch next {
            case '\'':
                builder.WriteRune('\'')
                i++
            case '"':
                builder.WriteRune('"')
                i++
            case '\\':
                builder.WriteRune('\\')
                i++
            case '0':
                // 注意:PHP 的 stripslashes 将 \0 还原为 NULL 字符
                builder.WriteRune('\x00')
                i++
            default:
                // 如果不是上述转义序列,保留反斜杠
                builder.WriteRune('\\')
            }
        } else {
            builder.WriteRune(runes[i])
        }
    }
    return builder.String()
}

func main() {
    input := "Is your name O\\'Reilly?"
    println(StripSlashes(input))
}

输出的结果:Is your name O'Reilly?