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
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
$x = 340.888888;
$y = floor($x);
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:
$x = "340.888888";
$y = preg_replace("/\..*$/", "", $x);
print_r($y);
The regex \..*$
means:
\. # match the literal '.'
.* # match any character except line breaks and repeat it zero or more times
$ # match the end of the string
You could also do...
$x = "340.888888";
$y = current(explode(".", $x));
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 as x*
, 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
as Foo 123
. The digit should appear ≥1 times. A +
should be used instead of a *
.
So your replacement should be
$y = preg_replace('/\\.\\d+/', "", $x);
(And to ensure the number to truncate is of the form 123.456
, not .456
, use a lookbehind.
$y = preg_replace('/(?<=\\d)\\.\\d+/', "", $x);
精彩评论