我有这个字符串:
[{"type":"date","label":"Champ Date de ","className":"form-control","name":"date-1545926599900"}]
我需要从标签中删除最后一个空格,实际值为“ Champ Date de”,我需要将其转换为“ Champ Date de”。
这是我的实际代码:
$form = str_replace('\n','',$request->getParameter('data'));
$form = str_replace('\t','',$form);
$form = str_replace(' ','',$form);
$form = str_replace('<br>','',$form);
var_dump($form); die;
问题来自
:str_replace('<br>','',$form);
的我没有问题,函数str_replace不会添加空格。但是使用<br>
在str_replace上添加一个空格,我确实需要在该值的末尾保留任何空格。希望有人可以帮忙。
我可以有多个数组:
'[{"type":"date","label":"Champ Date de ","className":"form-control","name":"date-1545929424866"},{"type":"checkbox-group","label":"You like it ? ","name":"checkbox-group-1545929428281","values":[{"label":"Option 1","value":"1","selected":true}]}]'
答案 0 :(得分:3)
使用array_map('trim',$array);
的非正则表达式方式如何?
<?php
$json = '[{"type":"date","label":"Champ Date de ","className":"form-control","name":"date-1545926599900"}]';
$array = json_decode($json,1)[0];
$array= array_map('trim',$array);
echo json_encode([$array]);
?>
输出:
[{"type":"date","label":"Champ Date de","className":"form-control","name":"date-1545926599900"}]
编辑:根据OP的评论
<?php
$json = '[{"type":"date","label":"Champ Date de ","className":"form-control","name":"date-1545929424866"},{"type":"checkbox-group","label":"You like it ? ","name":"checkbox-group-1545929428281","values":[{"label":"Option 1","value":"1","selected":true}]}]';
$array = json_decode($json,1);
$expected = [];
foreach($array as $k=>$v){
foreach($v as $key=>$value){
if($key == 'label' && !is_array($value)){
$expected[$k][$key]= trim($value);
}else{
$expected[$k][$key]= $value;
}
}
}
echo json_encode($expected);
?>
答案 1 :(得分:0)
您可以使用正则表达式来实现无循环运行 解决方法如下:
$string = '[{"type":"date","label":"Champ Date de ","className":"form-control","name":"date-1545929424866"},{"type":"checkbox-group","label":"You like it ? ","name":"checkbox-group-1545929428281","values":[{"label":"Option 1","value":"1","selected":true}]}]';
$pattern = '/("label":"([\w\s])+)/m';
echo preg_replace_callback($pattern, function($match) {return trim($match[0]);}, $string);
我已经为结果做了回声。您只需要将其分配给变量即可。