如何在 PHP 中删除最后一个逗号后面的字符串?
字符串:"this is a post, number 1, date 23, month 04, year 2012"
期望结果:"this is a post, number 1, date 23, month 04"
preg_replace
替换为空字符串。$until = preg_replace('/,[^,]*$/', '', $string);
这是Mario的回答的一种变体,适用于字符串中没有逗号的情况。
在第一步中,将字符串分割并删除创建的演示文稿中的最后一部分,然后再将数组合并
$tokens = explode(':', $string); // 使用 : 将字符串分割成数组 array_pop($tokens); // 删除数组中的最后一个元素 $newString = implode(':', $tokens); // 再次使用 : 合并数组为字符串