[英]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. 我正在使用Google Drive API,而我获得的
refresh_token
有一个转义正斜杠。 While this should be valid JSON, the API won't accept it when calling refreshToken()
. 虽然这应该是有效的JSON,但API在调用
refreshToken()
时不会接受它。 I am trying to remove the backslash using preg_replace
: 我试图使用
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
: 避免正则表达式,只需使用
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
嗯,有一个标准的功能就是这样:
stripslashes
So please avoid regex, str_replace et al. 所以请避免使用正则表达式,str_replace等。
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
1 / MgotwOvbwZN9MVxH5PrLR2cpvX1EJl8omgYdA9rrjx8
这对你有用:
$access_token = preg_replace('|\\\\|', '', $access_token);
What should happen to a string like this 1\\\\/Mg\\otw\\\\\\/Btow
? 像
1\\\\/Mg\\otw\\\\\\/Btow
这样的字符串会发生什么?
If your string uses double quote interpolated escapes, then a simple find \\/
replace /
won't work. 如果你的字符串使用双引号插值转义,那么一个简单的find
\\/
replace /
将不起作用。
You have to use this for a specific non-\\
escaped char: '~(?<!\\\\\\)((?:\\\\\\\\\\\\\\)*)\\\\\\(/)~'
您必须将此用于特定的
non-\\
转义字符: '~(?<!\\\\\\)((?:\\\\\\\\\\\\\\)*)\\\\\\(/)~'
Find - (?<!\\\\)((?:\\\\\\\\)*)\\\\(/)
查找 -
(?<!\\\\)((?:\\\\\\\\)*)\\\\(/)
Replace - $1$2
替换 -
$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/ 之前的名字:WOLVERINE WORLD WIDE INC / DE /
name after: WOLVERINE WORLD WIDE INC DE 之后的名字:WOLVERINE WORLD WIDE INC DE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.