简体   繁体   中英

PHP str_replace for back slash

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.

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 (ie 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!

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

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);

Stripslashes more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM