简体   繁体   English

php-从字符串的最后删除第n个字符

[英]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. 但会从最后删除所有4个字符。

You could use a regular expression. 您可以使用正则表达式。 Something like /\\},(\\s+)\\]/m should work. /\\},(\\s+)\\]/m应该可以工作。

$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. 但是,而不是固定这一部分,你应该修复代码,从而产生错误的, JSON字符串中。

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. 但是,我严格建议您这样做,并建议您假设尝试构造JSON字符串,则替换后端中形成此字符串的代码。

Hope this helps. 希望这可以帮助。

您也可以尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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