Reputation: 464
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?
Upvotes: 10
Views: 13045
Reputation: 56172
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);
Upvotes: 15
Reputation: 47903
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
Upvotes: 0
Reputation: 9740
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.
Upvotes: 8