有人能帮我从类似于字符串的字符串中提取维度吗?
Extending Garden Table 100 x 200 x 300 cm white
Extending Garden Table 200 x 200 cm black
Extending Garden Table 200 cm black Large根据字符串包含的内容,我只需要输出100 x 200 x 300 cm或200 x 200 cm或200 cm。
我从下面的代码开始,以防有帮助。
$string1 = "Extending Garden Table 100 x 200 x 300 cm white";
$test = get_dimensions($string1); //need it to output 100 x 200 x 300 cm
function get_dimensions($str) {
preg_match_all('/[0-9]{1,2}\X[0-9]{1,2}/i', $str, $matches);
//preg_match_all('!\d+!', $str, $matches);
return $matches;
}发布于 2021-09-04 20:51:49
您可以使用
\d+(?:\s*x\s*\d+)*\s*cm\b见regex演示。详细信息
\d+ -一个或多个数字(?:\s*x\s*\d+)* -零个或多个序列:\s*x\s* -包含零或多个空白空间的x\d+ -一个或多个数字\s* -零或多个空白空间cm -一个cm词\b -一个单词边界function get_dimensions($str) {
preg_match_all('/\d+(?:\s*x\s*\d+)*\s*cm\b/i', $str, $matches);
return $matches[0];
}
$string1 = "Extending Garden Table 100 x 200 x 300 cm white";
$test = get_dimensions($string1); //need it to output 100 x 200 x 300 cm
print_r($test);
// => Array ( [0] => 100 x 200 x 300 cm )若要提取带有小数部分的数字,请在上面模式中的每个(?:[,.]\d+)?后面添加(?:[,.]\d+)?(逗号或点的一个可选的出现,然后是一个或多个数字):
\d+(?:[,.]\d+)?(?:\s*x\s*\d+(?:[,.]\d+)?)*\s*cm\bhttps://stackoverflow.com/questions/69058776
复制相似问题