如何用“and"替换字符串中的最后一个逗号使用PHP? [英] How to replace last comma in string with "and" using php?

查看:53
本文介绍了如何用“and"替换字符串中的最后一个逗号使用PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 strrchr()str_replace() 用和"替换文本中最后一次出现的逗号.

I'm trying to replace the last occurence of a comma in a text with "and" using strrchr() and str_replace().

示例:

$likes = 'Apple, Samsung, Microsoft';
$likes = str_replace(strrchr($likes, ','), ' and ', $likes);

但这会替换整个最后一个单词(在本例中为 Microsoft),包括此字符串中的最后一个逗号.如何删除最后一个逗号并将其替换为和"?

But this replaces the entire last word (Microsoft in this case) including the last comma in this string. How can I just remove the last comma and replace it with " and " ?

我需要使用 strrchr() 作为函数来解决这个问题.这就是为什么这个问题没有重复而且更具体的原因.

I need to solve this using strrchr() as a function. That's why this question is no duplicate and more specific.

推荐答案

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

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.

这篇关于如何用“and"替换字符串中的最后一个逗号使用PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆