【问题标题】:How to escape backslashes to have safe strings ? php如何逃避反斜杠以获得安全的字符串? php
【发布时间】:2015-12-04 09:49:31
【问题描述】:

从昨天开始我就被这个问题困住了,我只是想了解如何正确地转义字符串,我没有找到任何完整的答案。

这是我的问题 =>

我有两个文件:

  1. replacement.txt,内容如下:

    new_content '\0020'

  2. subject.txt,内容如下:

    结构 old_content

这是我的代码:

$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_content '\0020',但它打印new_content 'structure old_content20'。为什么?因为有一个反斜杠没有转义。

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

  • 我曾尝试在preg_replace 之前添加$replacement = addslashes($replacement);:但这是我得到的:new_content \'\0020\',不正确,因为引号前有一个反斜杠。

  • 我曾尝试使用斜线斜线之前的结果$subject = stripslashes ( $subject ),但这是我得到的结果:new_content '020',不正确!


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


我不认为反斜杠的问题,因为如果我将replacement.txt 更改为new_content '\anyAlaphbetCharacter' 上面的代码(不带addlahes 和stripslash)将打印:new_content '\anyAlaphbetCharacter',这是正确的。

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

【问题讨论】:

  • @Uchiha 你可以看到我已经在使用它了,但这并没有帮助。

标签: php escaping octal addslashes


【解决方案1】:

我建议你一个技巧,就是在 preg_replace 之前用一些特殊的词替换 \,比如 [backslash],以避免它出现任何问题

$replacement = str_repalce(\`, [backslash], $replacement);`

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

$subject = str_repalce([反斜杠],\`,$subject);`

【讨论】:

  • 谢谢你的回答,是的,这是可行的,但我正在寻找正确的解决方案,我的意思是不使用技巧。
【解决方案2】:

发生了什么事。我认为 php 将\0 simbol 定义为"\0" (ASCII 0 (0x00)), the NUL-byte.

尝试使用 preg_quote() 函数。

【讨论】:

  • 感谢您的回答。但是 preg_quote() 会转义其他字符,例如 { ) ...这并不好。
猜你喜欢
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
  • 2011-11-23
  • 2022-11-24
  • 2015-11-10
  • 2016-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多