views:

387

answers:

4

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

+8  A: 

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.

Adam Wright
floor() will not cut off the digits on negative numbers but round down to the next lower negative number. If the digits have to be cut off, explicit casting will do that: $y = (int)$y; It's also faster.
Techpriester
`intval()` anyone?
Alix Axel
+1  A: 

You could also do...

$x = "340.888888";
$y = current(explode(".", $x));
fire
+1  A: 

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);
KennyTM
+1  A: 

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
Bart Kiers
thank you very much for the regex explication . It helps me a lot but Adam's answer servers better my goal so I need to mark his answer as accepted
Michael
@Michael, no problem. And I agree, if learning regex was not your main objective, then Adam's answer is definitely the way to go.
Bart Kiers