如何对字符串进行 URL 编码
$flr = preg_replace("/\\\'/","%27",$flr);
如果 URL 具有此符号:'
,则它会被 %27
替换,并且 URL 应变为 http://localhost/%27
,但是这个不起作用。
例如:
$flr = preg_replace("/\\\"/","%22",$flr);
URL 替换有效,我得到 http://localhost/%22
但是为什么我的第一个示例不起作用?
为了测试,我正在使用:
function isValidFLR(&$flr) {
$flr = preg_replace("/\\\'/","%27",$flr);
$flr = preg_replace("/\\\"/","%22",$flr);
echo $flr;
die();
}
$flr = preg_replace("/\\\'/","%27",$flr);
If URL has this symbol: '
it got replaced by %27
and the URL should become http://localhost/%27
, but this doesn't work.
For example:
$flr = preg_replace("/\\\"/","%22",$flr);
URL replacement works and I get http://localhost/%22
But then why doesn't my first example work?
To test, I'm using:
function isValidFLR(&$flr) {
$flr = preg_replace("/\\\'/","%27",$flr);
$flr = preg_replace("/\\\"/","%22",$flr);
echo $flr;
die();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您所要求的只是
urlencode()
?如果您只想替换几个特定字符,您也许应该尝试使用
str_replace()
。Is what you asking for simply
urlencode()
?If you just want to replace a couple of certain characters, you should perhaps try using
str_replace()
instead.会起作用的。
但是,正如其他人所说,执行此操作的 PHP 函数之一可能是更好的解决方案。
will work.
But, as others have said, one of the PHP functions which does this could be a better solution.
您遇到了 PHP 的字符串引号转义问题,与正则表达式的转义混合在一起。你可能会得到一个非常混乱的反斜杠序列!
解决您的问题的最直接的解决方案就是在搜索双引号时在正则表达式字符串上使用单引号:
但是,在您的情况下,一个更简单的解决方案正在乞求:为什么您需要使用正则表达式在这种情况下?一个简单的
str_replace()
也可以完成这项工作,并且可以避免所有那些令人毛骨悚然的斜线。You're having problems with PHP's string escaping of quotes, getting mixed in with regex's escaping. You could end up with a very messy sequence of backslashes!
The most direct solution for your problem is simply to use single quotes on your regex string when you're searching for double-quotes:
However, in your case, an even simpler solution is going begging: Why do you need to use regex at all in this case? A simple
str_replace()
would do this job just as well, and would avoid all those hair-raising slashes.如何测试以下内容:(
将 ' 替换为 ")
What about to test with following :
(replace ' to ")