使用模式从段落中提取数字

时间:2016-12-16 23:07:36

标签: php regex

我试图从特定模式中提取数字。

这是一个字符串"稳定患者的一个例子,包括3787和#34;

这个数字可以是患者之后或患者之前的任何地方。我想只提取特定单词之前或之后的第一组数字。

尝试使用它,但不能正常工作

function get_numerics ($str) {
    preg_match('/Patients\s*(\d+)/', $str, $matches);
    return $matches[0];
}

1 个答案:

答案 0 :(得分:0)

您可以使用两个正则表达式,一个用于查找关键字前的数字,另一个用于查找关键字后面的数字。如果找到任何一个,请计算关键字与数字之间的距离(以字符数表示)。然后根据计算出的距离返回最接近关键字的数字。您可能还想限制关键字和数字之间可能的最大距离;从关键字返回几百个字符的数字是没有意义的,对吧?我在下面使用了20个最大字符。

function get_numerics($str) {
    $word = 'patients';
    preg_match('/(\d+)[^\d]{1,20}?'.$word.'/i', $str, $matches_before);
    preg_match('/'.$word.'[^\d]{1,20}?(\d+)/i', $str, $matches_after);
    $distance_before = PHP_INT_MAX;
    $distance_after = PHP_INT_MAX;
    if (count($matches_before) == 2) {
        $distance_before = strlen($matches_before[0]) - strlen($matches_before[1]) - strlen($word);
    }
    if (count($matches_after) == 2) {
        $distance_after = strlen($matches_after[0]) - strlen($matches_after[1]) - strlen($word);
    }
    if (count($matches_before) == 2 || count($matches_after) == 2) {
        if ($distance_before < $distance_after) {
            return (int) $matches_before[1];
        } else {
            return (int) $matches_after[1];
        }
    }
    return FALSE;
}

var_dump(get_numerics("24 stable patients, including some"));
// Returns 24
var_dump(get_numerics("stable patients, including 3787 with"));
// Returns 3787
var_dump(get_numerics("24 stable patients, including 3787 with"));
// Returns 24, because it's the closest from the 'patients' keyword
var_dump(get_numerics("24 stable blablabla patients, including 3787 with"));
// Returns 3787, because it's the closest from the 'patients' keyword
var_dump(get_numerics("stable blablabla patients, including some that are not ok. But 3787 planes "));
// Returns FALSE, because 3787 is too far from the 'patients' keyword
相关问题