正規表現 小数点を含む数字をマッチさせたい

小数点前までマッチした

文字列は 10.54
返り値は 1
結果配列は Array ( [0] => 10 )

<?php
$str = 10.54;
$match = "\d+";

$rs1 = preg_match("/".$match."/", $str, $rs2);
print "文字列は ";
p($str);
print"返り値は ";
p($rs1);
print "結果配列は ";
p($rs2);


function p($o){
	print_r($o);
	print "<br>";
}
?>

少し改良して小数点以下もマッチした

文字列は 10.54
返り値は 1
結果配列は Array ( [0] => 10.54 )

<?php
$str = 10.54;
$match = "\d+\.\d+";

$rs1 = preg_match("/".$match."/", $str, $rs2);
print "文字列は ";
p($str);
print"返り値は ";
p($rs1);
print "結果配列は ";
p($rs2);


function p($o){
	print_r($o);
	print "<br>";
}
?>

小数点を含まない数字がマッチしなくなった

文字列は 10
返り値は 0
結果配列は Array ( )

<?php
$str = 10;
$match = "\d+\.\d+";

$rs1 = preg_match("/".$match."/", $str, $rs2);
print "文字列は ";
p($str);
print"返り値は ";
p($rs1);
print "結果配列は ";
p($rs2);


function p($o){
	print_r($o);
	print "<br>";
}
?>

小数点を含む数字と含まない数字の両方にマッチさせたい

文字列は 10
返り値は 1
結果配列は Array ( [0] => 10 )

文字列は 10.54
返り値は 1
結果配列は Array ( [0] => 10.54 [1] => .54 )

<?php
$str = 10;
//$str = 10.54;
$match = "\d+(\.\d+)?";

$rs1 = preg_match("/".$match."/", $str, $rs2);
print "文字列は ";
p($str);
print"返り値は ";
p($rs1);
print "結果配列は ";
p($rs2);


function p($o){
	print_r($o);
	print "<br>";
}
?>

後方参照はしたくない

文字列は 10.54
返り値は 1
結果配列は Array ( [0] => 10.54 )

<?php
$str = 10;
$str = 10.54;
$match = "\d+(?:\.\d+)?";

$rs1 = preg_match("/".$match."/", $str, $rs2);
print "文字列は ";
p($str);
print"返り値は ";
p($rs1);
print "結果配列は ";
p($rs2);


function p($o){
	print_r($o);
	print "<br>";
}
?>