英文:
How do I properly format a JSON payload in PHP without invalid whitespace for a REST API post call?
问题
需要在 JSON 字符串中删除空白/无效的空格,以便将其作为 REST API POST 调用的有效负载传递。
当前显示为:
{ "channel":{"id" : 6},"entryType" : {"id" : 1},"contentType": {"id": 2},"text":"
tttttt
" }
期望的结果是:
{ "channel":{"id" : 6}, "entryType" : {"id" : 1}, "text" : "Test1" }
将值分配给“text”键是动态的。
英文:
Need to remove whitespaces/invalid spaces in json string to pass as payload in rest api post call.
Currently it displaying:-
{ "channel":{"id" : 6},"entryType" : {"id" : 1},"contentType": {"id": 2},"text":"
tttttt
" }
Expecting:-
{ "channel":{"id" : 6}, "entryType" : {"id" : 1}, "text" : "Test1" }
Assigning the value to the "text" key is dynamic.
答案1
得分: 1
如果您想删除文本字段开头或结尾的空格,您可以使用 trim 函数:
https://www.php.net/manual/en/function.trim.php
$text = ' this is a test ';
$text = trim($text);
// $text ---> 'this is a test'
但是,如果目标是删除所有空格,我会使用 str_replace 函数:
https://www.php.net/manual/en/function.str-replace.php
$text = ' this is a test ';
$text = str_replace(' ', '', $text);
// $text ---> 'thisisatest'
这将消除所有空格,甚至文本之间的空格,所以如果您想传递完整的句子或段落,trim 将是一个更好的选项。
英文:
If you want to remove whitespaces at the beginning or end of the text field, you can use trim:
https://www.php.net/manual/en/function.trim.php
$text = ' this is a test ';
$text = trim($text);
// $test ---> 'this is a test'
But, if the objective were remove all whitespaces, I would use str_replace:
https://www.php.net/manual/en/function.str-replace.php
$text = $text = ' this is a test ';
$text = str_replace(' ', '', $text);
// $test ---> 'thisisatest'
This will eliminate all spaces, even between of the text, so if you want pass complete sentences or paragraphs, trim will be a better option.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论