svenyonson
svenyonson

Reputation: 1909

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.

Upvotes: 4

Views: 31314

Answers (7)

James Danforth
James Danforth

Reputation: 827

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

Upvotes: 0

anubhava
anubhava

Reputation: 784938

Avoid regex and just use str_replace:

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

Upvotes: 10

user557597
user557597

Reputation:

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

Upvotes: 0

Diego Agull&#243;
Diego Agull&#243;

Reputation: 9576

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

Upvotes: 13

Hanky Panky
Hanky Panky

Reputation: 46900

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

Output:

1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8

Upvotes: 1

Quixrick
Quixrick

Reputation: 3200

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

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

This will work for you:

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

Upvotes: 0

Related Questions