str_replace双引号和单引号

时间:2013-08-22 17:26:15

标签: php escaping str-replace

我有一个简单的PHP脚本,它应该使用反斜杠转义单引号和双引号。这是我的代码:

$output = str_replace('"','\"',$input);
$output = str_replace("'","\'",$output);
return $output;

问题是,它只会转义双引号,所以像

这样的字符串
"This" is a 'string'

解析为

\"This\" is a 'string'

\"This\" is a \'string\'

如果我将第二行更改为

$output = str_replace("'","asdf",$output);

我得到了

\"This\" is a asdfstringasdf

任何想法出了什么问题?

由于

3 个答案:

答案 0 :(得分:3)

我的代码没有问题,我的测试如下:

<?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\'

<强>被修改

现在不相关,OP想出来了:D

答案 1 :(得分:1)

试试这个:

$output = str_replace("\"","\\\"",$input);
$output = str_replace("\'","\\\'",$output);
return $output;

问题是'在字符串内部,应该注明为\',因为它是一个转义字符。反斜杠\在字符串中也是双\。

让我知道这是否有效。

答案 2 :(得分:0)

问题解决了。我在浏览器的控制台中查看输出,由于某种原因,它显示双引号的反斜杠,但不是单打。查看源显示它工作正常。

相关问题