-2

I have a string, $bodoy= 'this is data \\u003d\ this is data'; I want to urlencode() it, but when I urldecode() it gives me string like this. 'this is data \u003d\ this is data';

Note: I can't change the string, since it is coming from a thirdparty. Only want to ignore the escape sequences. so the result will same, after urldecode()

Required Result: this is data \\u003d\ this is data

Muhammad Arslan Jamshaid
  • 1,077
  • 8
  • 27
  • 48

1 Answers1

0

urlencode() and urldecode() are irrelevant, it is because of how you are entering the string in the source code.

To get the literal string this is data \\u003d\ this is data from a string assignment in PHP source code enclosed in double quotes, single quotes, or a HEREDOC you must escape all of the backslashes.

Eg:

$string = 'this is data \\\\u003d\\ this is data';
$string = "this is data \\\\u003d\\ this is data";
$string = <<<_E_
this is data \\\\u003d\\ this is data
_E_;

This is because \ is always an escape character which must itself be escaped. A lone backslash does not necessarily need to be escaped, but if you don't then a following character can be interpreted as an escape sequence, such as \\ collapsing to \ as you've seen.

The exception being the NOWDOC, where there is no escaping at all.

$string = <<<'_E_'
this is data \\u003d\ this is data
_E_;

Ref: https://www.php.net/manual/en/language.types.string.php

Sammitch
  • 30,782
  • 7
  • 50
  • 77
  • how can I add a variable in NOWDOC. if I have my string is `$dt=this is data \\u003d\ this is data` – Muhammad Arslan Jamshaid Jul 26 '22 at 06:46
  • @MuhammadArslanJamshaid _"how can I add a variable in NOWDOC"_ - you can't. Quote manual: _"A nowdoc is specified similarly to a heredoc, **but no parsing is done inside a nowdoc**."_ – CBroe Jul 26 '22 at 09:09