How to remove part of a string after last comma in

2020-02-11 06:44发布

How to remove part of a string after last comma in PHP ?

String : "this is a post, number 1, date 23, month 04, year 2012"
Expected: "this is a post, number 1, date 23, month 04"

3条回答
Viruses.
2楼-- · 2020-02-11 07:08
$tokens = explode(':', $string);      // split string on :
array_pop($tokens);                   // get rid of last element
$newString = implode(':', $tokens);   // wrap back

查看更多
再贱就再见
3楼-- · 2020-02-11 07:09

You want to replace the last comma and the rest, that is a comma followed by any other character until the end of the string.

This can be formulated as a regular expression and that pattern can be replaced via preg_replace with an empty string:

$until = preg_replace('/,[^,]*$/', '', $string);

This is a variant of mario's answer that works in case there is no comma in the string as well.

查看更多
▲ chillily
4楼-- · 2020-02-11 07:17

substr and strrpos would be useful

$until = substr($string, 0, strrpos($string.",", ","));

Note: edited based on comments below

查看更多
登录 后发表回答