package main import ( "errors" "fmt" "strconv" "strings" ) func phpUnquote(s string) (string, error) { if len(s) == 0 { return "", errors.New("expected quotes around string") } if s[0] == '"' { // Quote system is similar enough to Go's that strconv will probably just work // PROBLEM 1: PHP has some lax parsing for unknown escape sequences // e.g. regex("foo\.") will be silently parsed as regex("foo.") // PROBLEM 2: PHP supports multiline string literals, strconv.Unquote does not // Apply fixup s2 := strings.Replace(strings.Replace(s, "\r", `\r`, -1), "\n", `\n`, -1) ret, err := strconv.Unquote(s2) if err != nil { return "", fmt.Errorf("Parsing string literal `%s`: %v", s, err) } return ret, nil } if s[0] == '\'' { // Single-quotes escape fewer things unSQuo := strings.NewReplacer(`\'`, `'`, `\\`, `\`) return unSQuo.Replace(s[1 : len(s)-1]), nil } return "", errors.New("expected single/double quotes") }