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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Solution 2

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.

Solution 3

No capture groups are necessary. Just greedily match all characters in the string, then just before matching the last comma in the string, use \K to "forget" all previously matched characters. This effectively matches only the last occurring comma. Replace that comma with a space then the word "and".

Code: (Demo)

echo preg_replace('/.*\K,/', ' and', 'item 1, item 2, item 3');
// item 1, item 2 and item 3

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply