PHP - preg_match() 一个又一个词 [英] PHP - preg_match() word after other word

查看:62
本文介绍了PHP - preg_match() 一个又一个词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一段文字:这只猫出生于 1980 年,现在生活......

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

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).

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

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.

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

推荐答案

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

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];

输出:

1980 年

这篇关于PHP - preg_match() 一个又一个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆