Php 预匹配全部,选中+;抓斗(取下)
我在regex还是个不速之客。。但是学习和尝试;) 我想检查字符串是否以1800到2100之间的空格+年份号结尾 如果是这样,函数应该获取该数字(+从字符串中提取/删除) 这是我到目前为止得到的。。当然不行。但我必须靠近吗Php 预匹配全部,选中+;抓斗(取下),php,regex,preg-match,preg-match-all,Php,Regex,Preg Match,Preg Match All,我在regex还是个不速之客。。但是学习和尝试;) 我想检查字符串是否以1800到2100之间的空格+年份号结尾 如果是这样,函数应该获取该数字(+从字符串中提取/删除) 这是我到目前为止得到的。。当然不行。但我必须靠近吗 $thestring = 'Hello, the year is 1915'; $year = ''; if (preg_match_all('/ (18|19|20[0-9][0-9])$/', $thestring, $year)) { echo $thestri
$thestring = 'Hello, the year is 1915';
$year = '';
if (preg_match_all('/ (18|19|20[0-9][0-9])$/', $thestring, $year)) {
echo $thestring; // should not contain the year or last space anymore
echo $year[0]; // ?? should be the extracted year (without the space)
}
您可以使用此正则表达式:
/ (1[89][0-9]{2}|20[0-9]{2}|2100)$/
代码:
$thestring = 'Hello, the year is 1915';
if (preg_match('/ (1[89][0-9]{2}|20[0-9]{2}|2100)$/', $thestring, $year)) {
echo $year[1]; // should be the extracted year (without the space)
}
使用以下表达式:
/ ((?:18|19|20)[0-9]{2})$/
表达式的问题是交替嵌套。想想当你学习代数中的运算顺序,甚至嵌套多个条件时,比如:
if(A&&(B|C)){}
您的expression的捕获组在字符串末尾查找以下内容之一:
18
19
-2000
2099
18
、19
、或20
,然后是00-99
。请注意,我在交替中使用了非捕获组(?:…)
,而不是捕获组(…)
。如果我不这么做,你会看到我们会有:
- 1990年
- 十九,