简体   繁体   中英

php - remove nth character from last in string

How to remove specific character ',' from String from last index if exist.Is it possible to remove ?

{ "messages": [
    {
        "a": "a",
        "a": "",
        "a": "Title : Test Image",
        "a": "+923346455485"
    },{
        "a": "a",
        "a": "",
        "a": "Title : Test Image",
        "a": "+923346455485"
    },
]}

I want to remove last comma only from the string... which is },]} I want to remove the comma only..

I have tried this :

echo substr(trim($resultstr), 0, -4);

but it removes all the 4 characters from last.

You could use a regular expression. Something like /\\},(\\s+)\\]/m should work.

$data = preg_replace('/\},(\s+)\]/m', '}$1]', $data);

But instead of fixing this part, you should fix the code, which generates the wrong , inside the json string.

You can do something like this:

$str = '{"messages":[{"a":"a","a":"","a":"Title : Test Image","a":"+923346455485"},{"a":"a","a":"","a":"Title : Test Image","a":"+923346455485"},]}';

if (!empty(strrpos($str, '"},]'))) {
    $str[strrpos($str, ',', strrpos($str, '"},]'))] = '';
}

echo $str;

But I strictly advise against this and suggest you to replace the code where this string is formed in the Backend assuming you are trying to construct a JSON string.

Hope this helps.

您也可以尝试:

$string = substr_replace($string, '', strrpos($string, ','), 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM