Reputation: 3360
i am stuck in this question since yesterday, i just want to understanding how to escape strings correctly, i didn't found any full answer.
here is my issue =>
i have tow files:
replacement.txt , here is the content:
new_content '\0020'
subject.txt , here is the content:
structure old_content
here is my code:
$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 );
this code should print : new_content '\0020'
but it prints new_content 'structure old_content20'
.why? because there is a backslash that not escaped.
here is what i did but there is no luck :(
i had tried to add $replacement = addslashes($replacement);
before preg_replace
: but here is what i got:new_content \'\0020\'
, incorrect because there is a backslashed before quotes.
i had tried strip slash the previous result $subject = stripslashes ( $subject )
, but here is what i got: new_content '020'
, incorrect !
the only thing that worked for me, is to edit the replacement.txt
to this :
new_content '\\0020'
. but i can't change that manually , because it's an input from the user.
i don't think that the problem with the backslash , because if i change the replacement.txt
to new_content '\anyAlaphbetCharacter'
the above code (without addslahes and stripslash) will print : new_content '\anyAlaphbetCharacter'
and that's correct.
please help me to understand what's going on ?and what the solution ?
Upvotes: 1
Views: 203
Reputation:
What is going on. I think php defines \0
simbol as "\0" (ASCII 0 (0x00)), the NUL-byte.
Try use preg_quote() function.
Upvotes: 0
Reputation: 4202
i would suggest you one trick that is to replace \
with some special word like [backslash]
before preg_replace to avoid any problem with it
$replacement = str_repalce(
\`, [backslash]
, $replacement);`
then replace it back after preg_replace call
$subject = str_repalce(
[backslash],
\`,$subject);`
Upvotes: 1