Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP str_replace for back slash

Tags:

php

I need to replace \ with '' in following string.

$x = "FBU4061\0258";

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

It returns FBU40618,

Is there any workaround to get FBU40610258.

Note: I need to do this inside double quotes. Within single quotes it returns the desired value without problem.

like image 978
Shaolin Avatar asked Nov 09 '15 05:11

Shaolin


2 Answers

What's probably confusing you here is that double quoted strings interpret this string very differently from a single quoted string. Your string "FBU4061\0258" in PHP will interpret the \02 part of your string as an STX (or start of text) character (i.e. ASCII character 02).

Just try run the code var_dump("FBU4061\0258"); in PHP and see for yourself how the output is not what you would 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 all thoroughly documented behavior in the manual.

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

So in order to get a string literal of FBU4061\0258 you must escape the backslash inside of double quoted strings.

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

Notice this is because you are placing a string literal in your code. If this string were retrieved from your database, however, this interpolation wouldn't take place, because it's 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 the length of the string!

like image 90
Sherif Avatar answered Oct 26 '22 18:10

Sherif


Your best chance is to do a mysql replace query:

Change the value in the query:

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

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

You might also try this instead:

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

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

like image 27
Rens Tillmann Avatar answered Oct 26 '22 16:10

Rens Tillmann