Delete last comma from a string

1

I have a string: "imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg", ]

And I want to delete the last comma of it, leaving it like this: "imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg"]

How to do it?

    
asked by anonymous 26.03.2018 / 19:29

3 answers

4
// Remove os dois últimos caracteres
$str = substr($str, 0, strlen($str)-2);

// Acrescenta de volta o ]
$str .= ']';
    
26.03.2018 / 19:34
1

You can do this with the function str_replace

$string = '"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg", ]';

echo str_replace(', ]', ']', $string);

The result will be:

"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg"]

    
26.03.2018 / 19:50
0

See the following code snippet that removes the comma with or without space before the bracket.

<?php
/*A string que vc forneceu*/
$texto = '"imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg", ]';

/*Limpa String*/
echo preg_replace("/,(\s{1,}|)]/", "]", $texto);
?>
    
26.03.2018 / 19:59