Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the last comma in a string using Regular Expression

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?

like image 247
Alex Jose Avatar asked Jul 15 '11 10:07

Alex Jose


People also ask

How do I remove the last comma in Python?

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.

How do I remove the last comma from a string using PHP?

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), ',').

Can I use regex in replace?

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.


2 Answers

This regex matches the last coma: (,)[^,]*$

like image 132
Kirill Polishchuk Avatar answered Sep 28 '22 06:09

Kirill Polishchuk


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.

like image 43
ckruse Avatar answered Sep 28 '22 06:09

ckruse