从字符串php中提取weigth kg
你好,我有这样的绳子从字符串php中提取weigth kg,php,string,Php,String,你好,我有这样的绳子 $str = "tea dae 15 abc 7,2 kg abc aa 1 aa" 我只想得到这样的kg值 $str = "7,2kg"; 我试过了,但不起作用 $result = str_replace(' ', '', $str); $result = str_replace(',', '.', $result); $result = strtok($result, "kg"); $result = str_replace('.', ',',(float) fil
$str = "tea dae 15 abc 7,2 kg abc aa 1 aa"
我只想得到这样的kg值
$str = "7,2kg";
我试过了,但不起作用
$result = str_replace(' ', '', $str);
$result = str_replace(',', '.', $result);
$result = strtok($result, "kg");
$result = str_replace('.', ',',(float) filter_var( $result, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ));
感谢您的帮助您可以使用
$str = "tea dae 15 abc 7,2 kg abc aa 1 aa";
$result = "";
if (preg_match('~(\d+(?:,\d+)?)\s*(kg)\b~', $str, $m)) {
$result = $m[1] . $m[2];
}
echo $result;
看
正则表达式是
(\d+(?:,\d+)?)\s*(kg)\b
看。它会匹配的
\d+?:,\d+?-捕获组1:
\d+-一个或多个数字
?:,\d+?-逗号和一个或多个数字的可选序列
\s*-0或更多空格
kg\b-第2组中捕获的kg作为一个整体单词\b是单词边界。
最终结果是两个组的连接。您可以使用
$str = "tea dae 15 abc 7,2 kg abc aa 1 aa";
$result = "";
if (preg_match('~(\d+(?:,\d+)?)\s*(kg)\b~', $str, $m)) {
$result = $m[1] . $m[2];
}
echo $result;
看
正则表达式是
(\d+(?:,\d+)?)\s*(kg)\b
看。它会匹配的
\d+?:,\d+?-捕获组1:
\d+-一个或多个数字
?:,\d+?-逗号和一个或多个数字的可选序列
\s*-0或更多空格
kg\b-第2组中捕获的kg作为一个整体单词\b是单词边界。
最后的结果是两组的连接。@WiktorStribiżcharm@WiktorStribiżew谢意工作得很有魅力