Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove escaped forward slash using php?

Tags:

regex

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.

like image 741
svenyonson Avatar asked Dec 01 '22 02:12

svenyonson


2 Answers

Avoid regex and just use str_replace:

$access_token = "1\/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8";
$access_token = str_replace( '\/', '/', $access_token );
//=> 1/MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8
like image 180
anubhava Avatar answered Dec 05 '22 17:12

anubhava


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);
like image 24
Diego Agulló Avatar answered Dec 05 '22 17:12

Diego Agulló