php preg_replace ,我需要替换点后的所有内容(例如 340.38888 > 需要清理 340)
我需要替换点后的所有内容。我知道可以使用正则表达式来完成,但我仍然是新手,我不明白正确的语法,所以请帮助我。
我尝试了以下代码但不起作用:
$x = "340.888888"; $pattern = "/*./" $y = preg_replace($pattern, "", $x); print_r($x);
谢谢, 迈克尔
I need to replace everything after a dot . I know that it can be done with regex but I'm still novice and I don't understand the proper syntax so please help me with this .
I tried the bellow code but doesn't work :
$x = "340.888888"; $pattern = "/*./" $y = preg_replace($pattern, "", $x); print_r($x);
thanks ,
Michael
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我可能是错的,但这听起来就像使用 RegEx 锤子来解决一个非常非钉子形状的问题。如果您只是想截断正浮点数,则可以使用
编辑:正如 Techpriester 的评论所指出的,这将始终向下舍入(因此 -3.5 变为 -4)。如果这不是您想要的,您可以使用强制转换,如
$y = (int)$x
所示。I may be wrong, but this sounds like using the RegEx hammer for an eminently non-nail shaped problem. If you're just trying to truncate a positive floating point number, you can use
Edit: As pointed out by Techpriester's comment, this will always round down (so -3.5 becomes -4). If that's not what you want, you can just use a cast, as in
$y = (int)$x
.正如其他人已经提到的:有更好的方法来获取数字的整数部分。
但是,如果您问这个问题是因为您想学习一些正则表达式,请按以下步骤操作:
正则表达式
\..*$
表示:As already mentioned by others: there are better ways to get the integer part of a number.
However, if you're asking this because you want to learn some regex, here's how to do it:
The regex
\..*$
means:你也可以做...
You could also do...
正则表达式中的
.
表示“任何字符(换行符除外)。要实际匹配点,您需要将其转义为\.
。* 本身无效。它必须显示为
x*
,这意味着模式“x”重复零次或多次,您需要匹配一个数字,其中。另外
,您不想将
Foo... 123.456
替换为Foo 123
该数字应该出现 ≥1 次。应该使用+
而不是*
,因此您的替换应该是
(并确保要截断的数字的形式为
123.456
,而不是.456
,使用后视。The
.
in regex means "any characters (except new line). To actually match a dot, you need to escape it as\.
.The
*
is not valid by itself. It must appear asx*
, which means the pattern "x" repeated zero or more times. In your case, you need to match a digit, where\d
is used.Also, you wouldn't want to replace
Foo... 123.456
asFoo 123
. The digit should appear ≥1 times. A+
should be used instead of a*
.So your replacement should be
(And to ensure the number to truncate is of the form
123.456
, not.456
, use a lookbehind.