简体   繁体   English

除了最后一个w preg_replace之外,删除逗号

[英]Remove commas except last one w preg_replace

My head is spinning, I tried to do this on my own, but cant figure it out. 我的头在旋转,我试图自己做,但不能弄明白。 so once again I will turn to your guys knowledge. 所以我将再次转向你们的知识。

These all are my possible my strings: 这些都是我可能的字符串:

My head is spinning with, pregreplace
My head is spinning, with, pregreplace
My head is, spinning, with, pregreplace
My head, is, spinning, with, pregreplace

(Notice commas in above strings) (注意上面字符串中的逗号)

I want to have all "preg-replaced" / "string-replaced" with only one comma at the end.(Just like displayed on first example) 我希望所有“preg-replacement”/“string-replacement”最后只有一个逗号。(就像在第一个例子中显示的那样)

My head is spinning with, pregreplace 我的头在旋转,pregreplace

Thanks in advance ;) 提前致谢 ;)

You can use a "positive lookahead" like this: 您可以像这样使用“积极向前看”:

,(?=.*,)

The lookahead is the part in parens. 预测是parens中的一部分。 It basically says "only replace this comma if there's another comma later in the string. 它基本上说“如果字符串后面有另一个逗号,则只替换此逗号。

The code would look like this: 代码如下所示:

echo preg_replace('/,(?=.*,)/', '', $str);

I tested this with RegexBuddy to confirm it works: 我用RegexBuddy对此进行了测试以确认其有效:

在此输入图像描述

preg_replace( '/,/', '', $my_string, preg_match_all( '/,/', $my_string) - 1);

以上应该做你需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM