I'm trying to replace the last occurence of a comma in a text with "and" using strrchr()
and 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. How can I just remove the last comma and replace it with " and " ?
I need to solve this using strrchr()
as a function. That's why this question is no duplicate and more specific.
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
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()
because
strrchr()
willSee Doc here
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()
See Demo here
You can use regex to find last comma in string. Php
preg_replace()
replace string with another string by regex pattern.Check result in demo
To replace only the last occurrence, I think the better way is:
strrpos finds the position of last comma, and substr_replace puts the desired string in that place replacing '1' characters in this case.