简体   繁体   中英

How to remove escaped forward slash using php?

I am using the Google Drive API and the refresh_token I obtain has an escaped forward slash. While this should be valid JSON, the API won't accept it when calling refreshToken() . I am trying to remove the backslash using preg_replace :

$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = preg_replace('/\\\//', '/', $access_token);

I would like the returned string to be:

"1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";

I've tried various expressions, but it either doesn't remove the backslash or it returns an empty string. Note that I don't want to remove all backslashes, only the ones escaping a forward slash.

Avoid regex and just use str_replace :

$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = str_replace( '\/', '/', $access_token );
//=> 1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8

Well, there's a standard function that does just that: stripslashes

So please avoid regex, str_replace et al.

It's as simple as it takes:

$access_token = stripslashes($access_token);

You can use a different delimiter. Here I chose to use the ~ as a delimiter instead of the / .

$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = preg_replace('~\\\/~', '/', $access_token);

print $access_token;

This returns:

1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8
<?php
$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
echo str_replace("\\","",$access_token);
?>

Output:

1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8

这对你有用:

$access_token = preg_replace('|\\\\|', '', $access_token);

What should happen to a string like this 1\\\\/Mg\\otw\\\\\\/Btow ?

If your string uses double quote interpolated escapes, then a simple find \\/ replace / won't work.

You have to use this for a specific non-\\ escaped char: '~(?<!\\\\\\)((?:\\\\\\\\\\\\\\)*)\\\\\\(/)~'

Find - (?<!\\\\)((?:\\\\\\\\)*)\\\\(/)
Replace - $1$2

This works for me (uses negative forward lookahead):

$pattern = "/(?!\/)[\w\s]+/"
preg_match($pattern, $this->name,$matches)
$this->name = $matches[0]

name before: WOLVERINE WORLD WIDE INC /DE/

name after: WOLVERINE WORLD WIDE INC DE

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