Mathieu Mourareau
Mathieu Mourareau

Reputation: 1220

Php replace the last space in the label

I have this string :

[{"type":"date","label":"Champ Date de ","className":"form-control","name":"date-1545926599900"}]

I need to delete the last space from the label, the actual value is "Champ Date de " i need to convert it as "Champ Date de".

Here my actual code :

        $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;

The problem come from the
: str_replace('<br>','',$form);

with &nbsp; i have no problem and the function str_replace do not add a space. but with <br> the str_replace add a space add i really need to have any space at the end of this value. hope someone could help.

I could have multiple array :

'[{"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}]}]'

Upvotes: 0

Views: 200

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

How about this non-regex way with 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]);
?>

Output:

[{"type":"date","label":"Champ Date de","className":"form-control","name":"date-1545926599900"}]

DEMO: https://3v4l.org/qJ9K1

EDIT: As per OP's comment

<?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);
?>

DEMO: https://3v4l.org/NRlsR

Upvotes: 3

Gagan Prajapati
Gagan Prajapati

Reputation: 140

You can do it without loop by using regex Here is the solution:

$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);

I have done echo for the result. You just need to assign it to a variable.

Upvotes: 0

Related Questions