PHP将当前位置的最后一个字符替换为字符串的结尾

时间:2015-03-05 09:15:51

标签: php

我有这个字符串:

$string = '{"status":"2","vote":"1"},{"status":"1","vote":"0"}, "blabla"';

我想得到最后一次出现的位置'}'并删除其后的其余字符,然后附加']'。请帮忙。谢谢!

4 个答案:

答案 0 :(得分:0)

怎么样

$newString = substr($string,0,(strrpos($string,"}")+1))."]";

strrpos获取最后一个字符串

的位置

http://php.net/manual/en/function.strrpos.php

答案 1 :(得分:0)

你必须使用PHP函数strrpos(),它将从右侧首次出现字符串。

echo $newString = substr($string,0,strrpos($string,"}")+1)."]";

<强>输出

{"status":"2","vote":"1"},{"status":"1","vote":"0"}]

选中手动 strrpos()

答案 2 :(得分:0)

$string = '{"status":"2","vote":"1"},{"status":"1","vote":"0"}, "blabla"';
$newString = (substr($string, 0, strrpos($string, "}") + 1))."]";
echo $newString; //results: {"status":"2","vote":"1"},{"status":"1","vote":"0"}]

答案 3 :(得分:0)

使用原生json函数

$j=json_decode("[$string]");
array_pop($j);
echo json_encode($j);

或者在这种情况下你会遇到很多问题:

 $string = '{"status":"2","vote":"1"},{"status":"1","vote":"0"}, "bla}bla"';