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.
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.
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".
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 🙂