4

PHP で最後のカンマの後の文字列の一部を削除するには?

文字列:"this is a post, number 1, date 23, month 04, year 2012"
予想:"this is a post, number 1, date 23, month 04"

4

3 に答える 3

11

substrそしてstrrpos役に立つでしょう

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

注:以下のコメントに基づいて編集

于 2012-06-02T11:48:11.077 に答える
4

最後のカンマと残りのカンマを置き換えたいとします。つまり、カンマの後に文字列の終わりまで他の文字が続きます。

これは正規表現として定式化でき、そのパターンはpreg_replace空の文字列で置き換えることができます:

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

これは、文字列にコンマがない場合にも機能するマリオの回答の変形です。

于 2012-06-02T13:34:52.030 に答える