拆分数字并在点后保留一个数字
Split the number and keep one number after the dot
我有以下字符串:$string = "10x1.12A"
,我希望结果为:10x1.1
。最后我有不同的组合,但我只想在点后得到一个数字,然后删除所有数字。
我可能建议使用 preg_match_all
和正则表达式模式 ^.*?\.\d
:
$string = "10x1.12A";
preg_match_all ("/^.*?\.\d/", $string, $matches);
echo $matches[0][0];
这会打印:
10x1.1
也可能有一种 preg_replace
方法可以做到这一点:
$string = "10x1.12A";
$output = preg_replace("/(?<=\.\d).*$/", "", $string);
echo $output;
这种方法去除了出现在点号之后的所有内容。请注意,我在这里假设只有一个点。
$string = "10x1.12A" ;
$dotpos = strpos($string, '.'); // find the position of the first dot in the string
$result = substr($string, 0, $dotpos+2); // take the string from the start to the digit after the first dot
echo $result // 10x1.1
我有以下字符串:$string = "10x1.12A"
,我希望结果为:10x1.1
。最后我有不同的组合,但我只想在点后得到一个数字,然后删除所有数字。
我可能建议使用 preg_match_all
和正则表达式模式 ^.*?\.\d
:
$string = "10x1.12A";
preg_match_all ("/^.*?\.\d/", $string, $matches);
echo $matches[0][0];
这会打印:
10x1.1
也可能有一种 preg_replace
方法可以做到这一点:
$string = "10x1.12A";
$output = preg_replace("/(?<=\.\d).*$/", "", $string);
echo $output;
这种方法去除了出现在点号之后的所有内容。请注意,我在这里假设只有一个点。
$string = "10x1.12A" ;
$dotpos = strpos($string, '.'); // find the position of the first dot in the string
$result = substr($string, 0, $dotpos+2); // take the string from the start to the digit after the first dot
echo $result // 10x1.1