简体   繁体   English

如何删除所有特殊字符和空格,但逗号(,),冒号(:),双引号(“)和字符串的花括号除外

[英]How to remove all special characters and spaces except Comma(,), Colon(:),Double quote(") and curly braces of a string PHP

How can i clean this JSON String data ?. 我如何清理此JSON字符串数据? At first look it is very easy using str_replace method but its not. 乍一看,使用str_replace方法非常容易,但事实并非如此。 This JSON string is form JSON object that has spaces for ex . 此JSON字符串是JSON对象的形式,其中包含ex的空格。 {" First Name ": "something"} . {“名字”:“某事”}。 so when i converted this into json string the empty spaces replaced by unwanted strings(\ ) . 因此,当我将其转换为json字符串时,空白空间将替换为不需要的字符串(\\ u00a0)。 I think this problem can be solve using preg_replace but the suddenly i dont know the regex for comma,double quote,colon. 我认为可以使用preg_replace解决此问题,但突然之间我不知道逗号,双引号,冒号的正则表达式。 This characters is necessary for json string format. 对于json字符串格式,此字符是必需的。 Please help me. 请帮我。

for example 例如

       {"AS_applicant_Data__c":
            "{
                \"Last Name\u00a0\":\"SDFSAD\",
                \"First Name\u00a0\":\"SDFAFSDA\",
                \"Middle Name\u00a0\":\"SAFDSAFD\",
                \"Gender\u00a0\":\"Male\"
            }"
        }

to

        {"AS_applicant_Data__c":"
            "{
                "Last Name":"SDFSAD",
                "First Name":"SDFAFSDA",
                "Middle Name":"SAFDSAFD",
                "Gender":"Male"
            }"
        }

I use this code and it looks ok to me: 我使用此代码,对我来说没问题:

<?php

$string = <<<EOD
{"AS_applicant_Data__c":
    "{
        \"Last Name\u00a0\":\"SDFSAD\",
        \"First Name\u00a0\":\"SDFAFSDA\",
        \"Middle Name\u00a0\":\"SAFDSAFD\",
        \"Gender\u00a0\":\"Male\"
    }"
}
EOD;
$pattern = '#\\\\u[0-9a-f]{4}#i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);

?>

This regular expression is blindly replace Unicode char in a format of \\uxxxx with empty string. 此正则表达式盲目地将\\ uxxxx格式的Unicode char替换为空字符串。 If you know for certain that there's only \ , you can change regex to #\\\\\\\ #i 如果您确定只有\\ u00a0,则可以将正则表达式更改为#\\\\\\\ #i

Try a quick run here: http://ideone.com/xW4zTN 在这里尝试快速运行: http : //ideone.com/xW4zTN

When i use this preg_replace("/[^a-zA-Z]/", "", $str); 当我使用这个preg_replace("/[^a-zA-Z]/", "", $str); .. it will remove all the special characters. ..它将删除所有特殊字符。 is it possible to skip the comma,double quotes,curly braces and colon ? 是否可以跳过逗号,双引号,大括号和冒号?

Of course it is, just include those special characters in the character class (the quotation mark has to be escaped with a backslash): 当然可以,只需在字符类中包括这些特殊字符即可(引号必须使用反斜杠进行转义):

preg_replace("/[^a-zA-Z,\"{}:]/", "", $str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM