我有一个字符串:
我需要把它转换成:
实际上,只需用“and”替换最后一个逗号。有人能帮我吗?
"item 1, item 2, item 3"
。我需要把它转换成:
"item 1, item 2和item 3"
。实际上,只需用“and”替换最后一个逗号。有人能帮我吗?
"item 1, item 2, item 3"
。"item 1, item 2和item 3"
。,([^,]*)$
,它匹配最后一个逗号和逗号后的文本。$re = '/,([^,]*)$/m';
$str = 'item 1, item 2, item 3';
$subst = " and $1";
$result = preg_replace($re, $subst, $str);
$text = preg_replace('/(.*),/','$1 and',$text)
这个匹配到最后一个逗号并将其替换为没有逗号的内容。
\K
来“忘记”所有先前匹配的字符。这有效地仅匹配最后出现的逗号。用空格和单词“and”替换该逗号。echo preg_replace('/.*\K,/', ' and', 'item 1, item 2, item 3');
// item 1, item 2 and item 3