2

If you look at, for example, the revision history for this question (now deleted, need 10k rep) on Stack Overflow, the problem makes itself clear.

Specifically, look at the diff displayed for revision 5:

Now compare to the source for revision 4:

Consider the word: banana\'s
I'd like replace \' to get bananabas, thus replacing \' with "ba"

I tried the following but it doesn't work:
echo str_replace("\\\'", "ba", "banana\'s");

How would one do this in php?

Notice that the diff for revision 5 displays (in red highlight) the string "\\'" (with only 2 backslashes) as the first argument to str_replace() in the old version, but the source for revision 4 reveals that it was actually "\\\'" (with 3 backslashes) all along.

1 Answer 1

2

Nope, this is correct. In the Markdown of revision 4, there are indeed three backslashes at that spot, but the rendered version only has two. Look at the Markdown diff (third button from the top on the left side of the diff) of revision 5, and you'll see that the purpose of that revision was to enclose code in either backticks or code blocks.

Revision 4 had lots of code as plain text in it, and especially when it comes to backslashes, this makes a huge difference. Compare:

  1. The snippet from the example, as text:

    echo str_replace("\\'", "ba", "banana\'s");

  2. The snippet from the example, as code:

    echo str_replace("\\\'", "ba", "banana\'s");
    

Both of those have three backslashes in the first parameter; if you look at the source of this answer, you'll see that the only difference is indentation.

In non-code, a backslash can be used to escape characters that have special meaning in Markdown (example: \*stars, not italics\* -> *stars, not italics*). Thus the first two backslashes appear as only one in the rendered version, because the first escapes the second. The third appears on it's own, because it's followed by an apostrophe, which is not a special character in Markdown, and hence this backslash does not act as an escape.

In code, however, everything is literal: There are no escapes, and each backslash in the source creates a backslash in the final version.

Bottom line: In Revision 4, only two backslashes were visible in that particular spot in the rendered version, so the diff is absolutely correct.

2
  • Ah, true - good catch. Perhaps an option to allow setting which diff mode you view in by default would be useful? I'd personally prefer source diffs over render diffs, but that's definitely personal preference.
    – Amber
    Commented Oct 13, 2011 at 18:53
  • 1
    meta.stackexchange.com/questions/106109/…
    – balpha StaffMod
    Commented Oct 13, 2011 at 19:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .