-1

I am facing an issue with replacing () from a string. After using the below code snippet.

$str = "UPI\11770918"; echo str_replace('\', '~', $txn_desc);

After execution, I am getting the below response.

UPIO70918

My desired output was

UPI~11770918

Please help to solve this issue.

A.A Noman
  • 5,244
  • 9
  • 24
  • 46
  • 3
    The part `\117` denotes a octal number. Add another backslash to the first one, this will prevent the escape sequence from being triggered. – Honk der Hase Aug 24 '21 at 07:12
  • @Lars Stegelitz: If the questions are answered in the comments, they remain in the system as unanswered and can neither be rated nor accepted. – jspit Aug 24 '21 at 07:44
  • @umesh, you have to use like below `$str = 'UPI\11770918'; echo str_replace('\\', '~', $str);` use single quotation – A.A Noman Aug 24 '21 at 08:11
  • With single quote it's working but I am getting string in double quotes that why I got stuck – Umesh Singh Aug 24 '21 at 09:10
  • Reason not to reopen this page: https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php#:~:text=to%20display%20a,another%20backslash – mickmackusa Aug 24 '21 at 10:50

1 Answers1

0

\117 is interpreted as an ASCII character "O" in octal notation. So that the backslash loses its meaning, you have to escape it in the strings.

$str = "UPI\\11770918"; 
echo str_replace("\\", '~', $str);
// UPI~11770918

Without escaping, the string "UPI\11770918" remains unchanged in your code. This is only output as "UPIO70918" with an echo. The comparison

var_dump("UPI\11770918" === "UPIO70918");
//bool(true)

shows that both strings are identical.

jspit
  • 7,276
  • 1
  • 9
  • 17
  • I need to extract "11770918" from "UPI\11770918" can you please help me to get this value – Umesh Singh Aug 24 '21 at 09:08
  • I think the string contains something else and "UPI\11770918" is the wrong notation for your string. Please give the string with echo bin2hex($str); and show the result. – jspit Aug 24 '21 at 09:36