PHP str_replace for backslash

I need to replace \ with '' with the following line.

$x = "FBU4061\0258"; 

When I do $x = str_replace('\\', '', $x);

It returns FBU40618,

Is there any workaround for the FBU40610258.

Note. I need to do this inside double quotes. In single quotes, it returns the desired value without problems.

+5
source share
3 answers

Your best chance to make a mysql replacement request:

Change the value in the request:

SELECT REPLACE('http://yourdomain.com', 'http', 'https');

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace

Instead, you can try:

UPDATE table SET field_name = replace(field, 'http, 'https')

https://dba.stackexchange.com/questions/2261/how-do-i-remove-backslashes-from-records-in-mysql

+2
source

What is likely to confuse you is that double-quoted strings interpret this string very differently than a single quoted string. Your line "FBU4061\0258" in PHP will interpret part \02 your line as an STX character (or the beginning of the text) (i.e. ASCII 02 character).

Just try running the var_dump("FBU4061\0258"); code var_dump("FBU4061\0258"); in PHP and see for yourself how the result is not the one you expect. You can even do var_dump(bin2hex("FBU4061\0258")); and see the hexadecimal representation of your string for further clarification ...

Example

 var_dump(bin2hex('\02')); // string(6) "5c3032" var_dump(bin2hex("\02")); // string(2) "02" 

See the difference?

This is a fully documented behavior in the manual .

\[0-7]{1,3} sequence of characters matching a regular expression is a character in octal notation

So, to get the string literal FBU4061\0258 , you must avoid the backslash inside double- FBU4061\0258 strings.

 $x = "FBU4061\\0258"; $x = str_replace('\\', '', $x); var_dump($x); //string(11) "FBU40610258" 

Please note that this is because you are putting a string literal in your code. However, if this string was retrieved from your database, this interpolation would not have taken place, because it is already a string literal.

Again...

 var_dump("FBU4061\\0258"); // string(12) "FBU4061\0258" var_dump("FBU4061\0258"); // string(9) "FBU40618" 

Look at the obvious difference in string length!

+5
source

use php stripslashes

 echo stripslashes('FBU4061\0258'); 

or try this code: -

 function removeslashes($string) { $string=implode("",explode("\\",$string)); return stripslashes(trim($string)); } $text="FBU4061\0258"; echo removeslashes($text); 

More on stripslashes

0
source

Source: https://habr.com/ru/post/1235511/


All Articles