且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用“and"替换字符串中的最后一个逗号使用PHP?

更新时间:2023-02-22 12:30:46

为了只替换最后一次出现,我认为更好的方法是:

To replace only the last occurrence, I think the better way is:

$likes = 'Apple, Samsung, Microsoft';
$likes = substr_replace($likes, ' and', strrpos($likes, ','), 1);

strrpos 查找最后一个逗号的位置,并且 substr_replace 将所需的字符串放在该位置,在这种情况下替换 '1' 字符.

strrpos finds the position of last comma, and substr_replace puts the desired string in that place replacing '1' characters in this case.