2011-12-08 49 views
0

我有json数据作为传递给javascript的字符串。在字符串传递之前,我正在php中搜索所有双引号并替换它们。这工作正常,但一些JSON字符串有(看起来像)一个MS Word风格双引号,可能是斜体。所以我的<?php $t = str_replace("”", "", $t); ?>方法调用不是逃避特殊的双引号。str_replace来自单词的双引号

我需要找到charcode并转义吗?我尝试将字符串中的引号拼接起来,然后将其粘贴到php方法中,但它仍然不会将该字符识别为不同的双引号。

让我看看,如果我能在这里粘贴报价 - < “ >< ” >

谢谢。

+0

你为什么要替换它们? –

+0

是JSON格式的这些双引号部分还是他们自己的数据? –

+0

用户输入的一部分 –

回答

4
<?php 
function mb_str_replace($needle, $replacement, $haystack) { 
    return implode($replacement, mb_split($needle, $haystack)); 
} 
$t = "as“da”sd"; 
$t = mb_str_replace("”", "", $t); 
$t = mb_str_replace("“", "", $t); 
#and all the other weird quotes :) 
echo $t; 
?> 

http://php.net/manual/en/ref.mbstring.php

http://www.regular-expressions.info/unicode.html

我会建议使用的preg_replace代替

$t = "as“da”sd"; 
$t = preg_replace("/[”“]/u","",$t); #just create a character class 
echo $t; 

这可能是有用的: http://axonflux.com/handy-regexes-for-smart-quotes

+0

感谢您的详细信息@jackdoe/u表示什么...它给我'编译失败:错误0时出现无效的UTF-8字符串错误。 –

+0

@TimJoyce http://php.net/manual/en/reference.pcre.pattern.modifiers.php – jackdoe

+0

@TimJoyce btw,不要忘记以UTF-8格式保存你的php,否则你将不得不输入字符代码具体的引号,因为即使他们在编辑器后看起来OK,他们可能会被屠杀,然后即使第一个str_replace也可以工作,但是当我使用unicode时,我总是倾向于特定的,所以我确信函数i我使用知道它是unicode – jackdoe

1

我尝试过自己,所以只有我可以想出你必须使用UTF-8编码。

<?php 
    header('content-type: text/html; charset=utf-8'); 
    $str = "“ > and < ”\""; 
    $replaceArr = array("“", "”", "\""); 
    $replaced = str_replace($replaceArr,"",$str); 
    echo $replaced; 
?> 

当我尝试它时看起来很干净。