str_replace双引号和单引号
I have a simple PHP script that should escape both single and double quotes with a backslash. Here is my code:
$output = str_replace('"','\"',$input);
$output = str_replace("'","\'",$output);
return $output;
Problem is, it only escapes the double quote, so a string like
"This" is a 'string'
parses out to be
\"This\" is a 'string'
not
\"This\" is a \'string\'
If I change the second line to
$output = str_replace("'","asdf",$output);
I get
\"This\" is a asdfstringasdf
Any ideas what is going wrong?
Thanks
我有一个简单的PHP脚本,它应该用反斜杠转义单引号和双引号。 这是我的代码: p>
$ output = str_replace('“','\'',$ input);
$ output = str_replace(”'“,”\ '“,$ output);
return $ output;
code> pre>
问题是,它只会转义双引号,所以像 p>
这样的字符串 n
“This”是一个'字符串'
code> pre>
解析为 p>
\“这个\”是一个'字符串'
code> pre>
不是 p>
\“这个\”是一个\ 'string \'
code> pre>
如果我将第二行更改为 p>
$ output = str_replace(“'” ,“asdf”,$ output);
code> pre>
我得到 p>
\“这个\”是一个asdfstringasdf
code> pre>
任何想法出了什么问题? p>
谢谢 p>
div>
Problem solved. I was viewing the output in my browser's console, which for some reason was showing the backslash for double quotes, but not singles. View source showed that it was working properly.
Try this:
$output = str_replace("\"","\\\"",$input);
$output = str_replace("\'","\\\'",$output);
return $output;
The problem is that ' inside a string, should be noted as \' , as it is an escape character. The backslash \ is a double \ as well inside a string.
Let me know if this works.
I didn't have a problem with your code, my test is below:
<?php
$input = '"This" is a '."'".'String'."'";
echo $input.'<br />';
//Echos "This" is a 'String'
$output = str_replace('"','\"',$input);
$output = str_replace("'","\'",$output);
echo $output;
//Echos \"This\" is a \'String\'
Edited
Irrelevant now, OP figured it out :D