PHP - preg_match() word after other word

冷暖自知 提交于 2021-02-05 09:27:35

问题


I have a text like this one: The cat was born on 1980 and lives ...

So i want to get the cat's age with regex (the text could have more than 1 occurrence of a number with 4 digits).

I'm trying this preg_match('/born on [0-9]{4}/', $text, $matches) but the result is: array('born on 1980'). I want to ignore everything before a year.

Demo: http://www.phpliveregex.com/p/aYl


回答1:


Group the value you want then it will be the first item of the array.

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

Output:

1980



来源:https://stackoverflow.com/questions/29907526/php-preg-match-word-after-other-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!