9

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?

3 Answers 3

13

You can use this regex: ,([^,]*)$, it matches the last comma and text after it.

$re = '/,([^,]*)$/m';
$str = 'item 1, item 2, item 3';
$subst = " and $1";

$result = preg_replace($re, $subst, $str);
8

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.

2
  • can u explaing wat that $1 ll do... i waiting for ur answer
    – K6t
    Commented Jul 16, 2011 at 10:25
  • 1
    In regexes you can save parts of the matched string in so-called back references. You define a back reference by putting braces around a part of the expression. You can refer to the references by $1 to $9 or by \1 to \9. So $1 is the value of the first back reference, (.*) in this case.
    – ckruse
    Commented Jul 16, 2011 at 11:55
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.