简体   繁体   English

如何从php中的“(引号)之外剥离标签等?

[英]How to strip tabs etc from outside of " (quotes) in php?

I have user entered JSON. 用户输入了JSON。 This means I sometimes get tabs, newlines etc outside of quotes where they are making it pretty. 这意味着有时我会在引号之外添加标签,换行符,使它们更漂亮。 Prior to processing I'd like to strip these unwanted characters. 在处理之前,我想去除这些不需要的字符。

For example (from log): 例如(从日志):

{#015#012#011#011#011#011"dest":"dest@email.com",#015#011#011#011#011"sender":"sender@email."}

In reality 事实上

{\r\n\t\t\t\t"dest":"dest@email.com",\r\n\t\t\t\t"sender":"sender@email."}

How can I strip these unwanted characters from outside the quotes, without affecting deliberate characters inside the quotes? 如何在引号外去除这些不需要的字符,而又不影响引号内的故意字符?

You don't need to strip out "\\t" or "\\n" in this case. 在这种情况下,您不需要去除“ \\ t”或“ \\ n”。 All you have to do is json_decode the string, and you will get the correct key/value pairs. 您所要做的就是json_decode字符串,您将获得正确的键/值对。

$json = "{\t \t\n \"dest\":\"dest@email.com\",\r\n \t\"sender\":\"sender@email.\"}";
foreach(json_decode($json,TRUE)as $key=>$value){
    echo "#$key:$value#\n";
} 

Output: 输出:

#dest:dest@email.com#
#sender:sender@email.#

As you can see, the "\\t" and "\\n" are not part of the key. 如您所见,“ \\ t”和“ \\ n”不是键的一部分。 More over, and in the general case, if those characters are part of the value, you may want to keep them intact (an example would be a multi-line uer address) 此外,在一般情况下,如果这些字符是值的一部分,则您可能希望保持它们不变(例如多行用户地址)

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

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