PHP: Text Processing preg_match function

2019-06-10 02:26发布

问题:

<?php
$eqn1="0.068683000000003x1+2.046124y1+-0.4153z1=0.486977512";
preg_match("/\b[0-9]*\b/",$eqn1,$vx1);
echo "X1 is: $vx1[0]";
?>

Can someone tell me, how to store the value of x1 (that is, 0.068683000000003) in the variable $vx1?

The output is:

X1 is: 0

回答1:

1)put semicolon after each sentences;
2)use echo "X1 is:" $vx1[0]; instead ofecho "X1 is: $vx1[0]";

<?php
   $eqn1="0.068683000000003x1+2.046124y1+-0.4153z1=0.486977512";

   preg_match("/\b[0-9]*\b/",$eqn1,$vx1);
   echo "X1 is:" .$vx1[0];


回答2:

You are missing semicolons after statements and the echo statement has to be modified:

<?php
$eqn1 = "0.068683000000003x1+2.046124y1+-0.4153z1=0.486977512";

preg_match("/\b[0-9]*\b/", $eqn1, $vx1);
echo "X1 is: " . $vx1[0];


回答3:

Your regex takes into account only integer, your first numùber is a decimal one.

Here is a way to do the job, the number you're looking for is in group 1:

$eqn1 = "0.068683000000003x1 + 2.046124y1 + -0.4153z1 = 0.486977512";
preg_match("/^(\d+\.\d+)/", $eqn1, $vx1);
echo "X1 is: ", $vx1[1], "\n";

Output:

0.068683000000003