I have a string like:"item 1, item 2, item 3"
.
What I need is to transform it to:"item 1, item 2 and item 3"
.
In fact, replace the last comma with " and". Can anyone help me with this?
rstrip() method only removes the comma if it's the last character in the string. The str. rstrip() method would remove all trailing commas from the string, not just the last one. Alternatively, you can use the str.
Use the rtrim function: rtrim($my_string, ','); The Second parameter indicates the character to be deleted. Also make sure you don't have any trailing space after the comma, otherwise this will fail, or do rtrim(trim($my_string), ',').
The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.
This regex matches the last coma: (,)[^,]*$
Use greediness to achieve this:
$text = preg_replace('/(.*),/','$1 and',$text)
This matches everything to the last comma and replaces it through itself w/o the comma.
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