简体   繁体   English

如何用“和”替换字符串中的最后一个逗号?

[英]How to replace last comma in string with “and” using php?

I'm trying to replace the last occurence of a comma in a text with "and" using strrchr() and str_replace() . 我正在尝试使用strrchr()str_replace()用“和”替换文本中逗号的最后一次出现。

Example: 例:

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

But this replaces the entire last word (Microsoft in this case) including the last comma in this string. 但这取代了整个最后一个单词(在本例中为Microsoft),包括此字符串中的最后一个逗号。 How can I just remove the last comma and replace it with " and " ? 如何删除最后一个逗号并将其替换为“和”?

I need to solve this using strrchr() as a function. 我需要使用strrchr()作为函数来解决这个问题。 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 finds the position of last comma, and substr_replace puts the desired string in that place replacing '1' characters in this case. strrpos查找最后一个逗号的位置,substr_replace将所需的字符串放在该位置,在这种情况下替换“1”字符。

You can use regex to find last comma in string. 您可以使用正则表达式查找字符串中的最后一个逗号。 Php preg_replace() replace string with another string by regex pattern. Php preg_replace()通过regex模式将字符串替换为另一个字符串。

$likes = 'Apple, Samsung, Microsoft';
$likes = preg_replace("/,([^,]+)$/", " and $1", $likes)

Check result in demo 演示中检查结果

first, you gotta separate the elements into an array with all but the last one, and the last one. 首先,你必须将元素分成一个数组,除了最后一个,最后一个。 then you put them back together with commas and an "and", respectively 然后你分别用逗号和“和”把它们放回去

$likes = "A, B, C";
$likes_arr = explode(",", $likes);
$last = array_pop($likes_arr);
$likes = implode(",", $likes_arr) . " and" . $last;
echo $likes; //"A, B and C";

however: don't forget to check if you actually have enough elements. 但是:不要忘记检查你是否确实有足够的元素。 this fails for inputs without comma. 没有逗号的输入失败。

just provide the answer with function strrchr() 只是提供函数strrchr()的答案

$likes = 'Apple, Samsung, Microsoft';
$portion = strrchr($likes, ',');
$likes = str_replace($portion, (" and" . substr($portion, 1, -1)), $likes);

because strrchr() will 因为strrchr()

This function returns the portion of string 此函数返回字符串的一部分

See Doc here Doc

so we just need only replace the comma symbol should be fine. 所以我们只需要替换逗号符号就可以了。 and the comma will be always the first character when you use strrchr() 当你使用strrchr()时,逗号将始终是第一个字符

See Demo here 在这里演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM