Php preg_replace, I need to replace everything after the point (for example, 340.38888> need to clear 340)

I need to replace everything after the point. I know this can be done with a regex, but I'm still a newbie and I don't understand the correct syntax, so please help me with this.

I tried the following code but did not work:

  $ x = "340.888888";
$ pattern = "/*./"
 $ y = preg_replace ($ pattern, "", $ x);
print_r ($ x);

thanks michael

+3
source share
4 answers

I may be wrong, but it is like using a RegEx hammer to solve a problem other than a nail. If you are just trying to truncate a positive floating point number, you can use

$x = 340.888888;
$y = floor($x);

: Techpriester, ( -3.5 -4). , , , $y = (int)$x.

+9

: .

, , , :

$x = "340.888888";
$y = preg_replace("/\..*$/", "", $x);
print_r($y);

\..*$ :

\.    # match the literal '.'
.*    # match any character except line breaks and repeat it zero or more times
$     # match the end of the string
+3

...

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

. " ( ). , \..

*invalid by itself. It should look like x*, which means that the pattern "x" is repeated zero or more times. In your case, you need to match the number where it is used \d.

In addition, you will not want to replace Foo... 123.456with Foo 123. The number should appear ≥1 times. A +should be used instead *.

So your replacement should be

$y = preg_replace('/\\.\\d+/', "", $x);

(And to ensure that the truncation number is of the form 123.456, and not .456, use lookbehind.

$y = preg_replace('/(?<=\\d)\\.\\d+/', "", $x);
+1
source

Source: https://habr.com/ru/post/1745639/


All Articles