简体   繁体   English

正则表达式从字符串PHP中删除year

[英]Regex to remove year from a string PHP

I have created a database of cigarette and trading cards. 我已经创建了香烟和交易卡的数据库。 Each set title has a year associated with it. 每个设置标题都有与之关联的年份。 For example, 1943 or 2011 . 例如19432011 The year is always 4 characters long, but can be anywhere in the string. 年份始终为4个字符,但可以在字符串中的任何位置。

Could someone please help me create a regex that will find the year in the string. 有人可以帮我创建一个可在字符串中查找年份的正则表达式。 I tried '/d{4}\\b/' but it is failing. 我尝试了'/d{4}\\b/'但是失败了。

(19|20)[0-9][0-9]

这将仅在1900年和2000年的范围内显示。

Try this one : 试试这个:

/\b\d{4}\b/

it will match 4 digits embeded with non-words 它将匹配嵌入非单词的4位数字

Here is a full solution: 这是一个完整的解决方案:

$stringWithYear = '1990 New York Marathon';
$stringNoYear = preg_replace('/(19|20)[0-9][0-9]/', '', $stringWithYear);
echo trim($stringNoYear);  // outputs 'New York Marathon'

d{4}\\b will match four d 's at a word boundary. d{4}\\b将在单词边界匹配四个d You forgot the backslash in the character class: should be \\d{4}\\b . 您忘记了字符类中的反斜杠:应该为\\d{4}\\b Depending on the input data you may also want to consider adding another word boundary ( \\b ) at the beginning. 根据输入数据,您可能还需要考虑在开头添加另一个单词边界( \\b )。

This too works.. preg_match("/^1[0-9]{3}$/",$value)) preg_match(“ / ^ 1 [0-9] {3} $ /”,$ value))也是如此。

Checks year of only starting with 1. You could change according to your requirement.. 仅从1开始检查年份。您可以根据需要进行更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM