简体   繁体   English

preg_match括号模式

[英]preg_match parenthesized pattern

I'm trying to change a bunch of decimals in a string to two decimal points. 我正在尝试将字符串中的一串小数更改为两个小数点。 The regex seems to match it just fine. 正则表达式似乎匹配它就好了。 The problem is with the replace. 问题在于更换。

This is my code: 这是我的代码:

$input_lines = "-33.873293252 151.201538015999972,-33.873175 151.201689183999946";

print preg_replace("/[0-9]+(\.[0-9][0-9]?)?/", "$0 $2", $input_lines);

Which outputs decimal that I want | 哪个输出我想要的小数 | truncated decimals that I don't want : 我不想要的截断的小数

 -33.87 3293252  151.20 1538015999972 ,-33.87 3175  151.20 1689183999946 

So I tried changing the replacement to $0 . 因此,我尝试将replacement更改为$0 But now the replace stopped working, and is instead giving me: 但是现在替换不再起作用了,而是给了我:

-33.873293252 151.201538015999972,-33.873175 151.201689183999946

How can I rewrite my regular expression so it gives me the desired output? 我该如何重写我的正则表达式,使其提供所需的输出?

Better: 更好:

preg_replace("/(?<=\.\d\d)\d+/","",$input_lines);

Replaces all trailing decimals after the first two with nothing. 将前两位后的所有尾随小数部分全部替换为空。

([-+]?\d+(?:\.\d{2})?)(\d*)

Try this.Replace by $1 .See demo. 试试这个,用$1代替。

https://regex101.com/r/vD5iH9/46 https://regex101.com/r/vD5iH9/46

$re = "/([-+]?\\d+(?:\\.\\d{2})?)(\\d*)/m";
$str = "-33.873293252 151.201538015999972,-33.873175 151.201689183999946";
$subst = "$1";

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

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

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