Delete last comma from a string

Asked

Viewed 471 times

1

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

And I want to rule out her last comma by letting it stay that way: "imagens":["upload/7057c705298193c513f07fbb8fbe2856.jpg", "upload/30c2dbcd5c890e763fab6ccfa63ab24c.jpg", "upload/40f4af351cfa1d01ca2e468965d28626.jpg"]

How to do?

  • Probably this is a problem in the generation of the string, better than taking the comma is not even putting it. But to be sure, only seeing the code that generates the string.

3 answers

3


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

// Acrescenta de volta o ]
$str .= ']';

0

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"]

0

See the following Code snippet that removes the comma with or without space before the square 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);
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.