首页 > 解决方案 > php打印双斜线而不是只有1

问题描述

我从 config.ini 中读取了一个字符串,该字符串是

config.ini
[section]
param = "#1234\y"

然后当我阅读此代码并将其打印在日志中或尝试将其发送到服务器或套接字时,这将打印以下内容:

#1234\\y

如何确保只发送一个反斜杠

当我从没有 \y 的配置中获取时也是如此。并尝试通过像 $x.'\y' 这样的 php 连接它,它是相同的并且不起作用。

仅当我使用字符串而不是配置定义变量时,它才有效

我的 udp 服务器我需要发送字符串

    //Send the message to the server
    if( ! socket_sendto($sock, $newstr , strlen($newstr) , 0 , $ip , $port))
    {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        throw new Exception("Could not send data: $errorcode $errormsg \n");
    }

标签: phpstring

解决方案


问题是错误地转义输入- 而不是错误地转义输出。

要么尝试parse_ini_file ($filename, true, INI_SCANNER_RAW);禁用解析,这将导致不转义反斜杠 - 要么INIparam = '#1234\y'.

如果无法修复字符串输入,以下是修复输出字符串的方法(最糟糕的解决方案):

$newstr = str_replace('\\\\', '\\', $mystr);

或者

$newstr = preg_replace('/\\\\/', '\\', $mystr);

推荐阅读