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.
To remove comma, you can replace. To replace, use str_replace() in PHP.
To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed. Copied!
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.
You can use regex to find last comma in string. Php preg_replace()
replace string with another string by regex pattern.
$likes = 'Apple, Samsung, Microsoft';
$likes = preg_replace("/,([^,]+)$/", " and $1", $likes)
Check result in demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With