【发布时间】:2015-12-04 09:49:31
【问题描述】:
从昨天开始我就被这个问题困住了,我只是想了解如何正确地转义字符串,我没有找到任何完整的答案。
这是我的问题 =>
我有两个文件:
-
replacement.txt,内容如下:
new_content '\0020'
-
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