PHP - preg_match() 逐字逐句

PHP - preg_match() word after other word

我有这样一条短信:The cat was born on 1980 and lives ...

所以我想用正则表达式获取猫的年龄(文本可能出现超过 1 次 4 位数字)。

我正在尝试 preg_match('/born on [0-9]{4}/', $text, $matches),但结果是:array('born on 1980')。我想忽略一年前的一切。

演示:http://www.phpliveregex.com/p/aYl

将您想要的值分组,然后它将成为数组的第一项。

$text = 'The cat was born on 1980 and lives ...';
preg_match('/born on ([0-9]{4})/', $text, $matches);
echo $matches[1];

输出:

1980