如何避开反斜杠以获得安全的字符串?php

如何避开反斜杠以获得安全的字符串?php,php,escaping,octal,addslashes,Php,Escaping,Octal,Addslashes,从昨天起我就一直在问这个问题,我只是想了解如何正确地转义字符串,我没有找到任何完整的答案 这是我的问题=> 我有两个文件: replacement.txt,内容如下: 新内容“\0020” subject.txt,内容如下: 结构旧内容 这是我的密码: $myfile = fopen ( __DIR__ . '/replacement.txt', "r" ) or die ( "Unable to open file!" ); $replacement = fread ( $myfile, fi

从昨天起我就一直在问这个问题,我只是想了解如何正确地转义字符串,我没有找到任何完整的答案

这是我的问题=>

我有两个文件:

  • replacement.txt,内容如下:

    新内容“\0020”

  • subject.txt,内容如下:

    结构旧内容

  • 这是我的密码:

    $myfile = fopen ( __DIR__ . '/replacement.txt', "r" ) or die ( "Unable to open file!" );
    $replacement = fread ( $myfile, filesize ( __DIR__ . '/replacement.txt' ) );
    fclose ( $myfile );
    
    
        $myfile = fopen ( __DIR__ . '/subject.txt', "r" ) or die ( "Unable to open file!" );
        $subject = fread ( $myfile, filesize ( __DIR__ . '/subject.txt' ) );
        fclose ( $myfile );
    
        $subject = preg_replace ( "%structure.*%s", $replacement, $subject, - 1, $count );
        die ( $subject );
    
    此代码应该打印:
    new\u content'\0020'
    但它打印的是
    new\u content'structure old\u content20'
    。为什么?因为有一个反斜杠没有漏掉

    以下是我所做的,但没有运气:(

    • 我试图在
      preg\u replace
      之前添加
      $replacement=addslashes($replacement);
      :但我得到的结果是:
      new\u content\'\0020\'
      ,不正确,因为引号前有反斜杠

    • 我曾经尝试过删除以前的结果
      $subject=stripslashes($subject)
      ,但我得到的结果是:
      新内容“020”
      ,不正确


    唯一对我有效的方法是将
    replacement.txt
    编辑为:
    new\u content'\\0020'
    。但我无法手动更改,因为这是用户的输入


    我不认为反斜杠有问题,因为如果我将
    replacement.txt
    更改为
    new\u content'\anyAlaphbetCharacter'
    以上代码(没有AddSlaches和stripslash)将打印:
    new\u content'\anyAlaphbetCharacter'
    ,这是正确的


    请帮助我了解发生了什么?以及解决方案是什么?

    我建议你一个技巧,就是在preg\u replace之前用一些特殊的词替换
    \
    ,如
    [反斜杠]
    ,以避免出现任何问题

    $replacement=str\u replace(
    \`,
    [反斜杠]
    ,$replacement)`

    然后在调用preg_replace后将其替换回


    $subject=str\u repalce(
    [backslash]
    \`,$subject);`

    发生了什么事。我认为php将
    \0
    simbol定义为
    “\0”(ASCII 0(0x00)),NUL字节。


    尝试使用preg_quote()函数。

    谢谢您的回答,是的,这很有效,但我正在寻找正确的解决方案,我的意思是不使用技巧。@Uchiha您可以看到我已经在使用它,但这没有帮助。谢谢您的回答。但是preg_quote()将转义其他字符,如{)…这不好。