1

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

这是我的问题=>

我有两个文件:

  1. replacement.txt ,这是内容:

    新内容'\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'。为什么?因为有一个反斜杠没有逃脱。

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

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

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


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


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

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

4

2 回答 2

1

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

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

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

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

于 2015-12-04T10:06:12.713 回答
0

到底是怎么回事。我认为 php 将\0simbol 定义为"\0" (ASCII 0 (0x00)), the NUL-byte.

尝试使用 preg_quote() 函数。

于 2015-12-04T11:09:40.477 回答