1

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:

  1. replacement.txt , here is the content:

    new_content '\0020'

  2. 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 ?

1
  • @Uchiha you could see that i'v already use it , but that doesn't help.
    – david
    Dec 4, 2015 at 10:16

2 Answers 2

1

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);`

1
  • thank you fro your answer, yes that's works , but i am searching for the correct solution, i mean without using tricks.
    – david
    Dec 4, 2015 at 10:14
0

What is going on. I think php defines \0 simbol as "\0" (ASCII 0 (0x00)), the NUL-byte.

Try use preg_quote() function.

1
  • thank you for your answer. but preg_quote() will escape other character like { ) ... and that's not good.
    – david
    Dec 4, 2015 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.