Extract year from a string using PHP regex

陌路散爱 提交于 2021-01-27 19:02:23

问题


I want to extract year from a string. I got an incomplete solution. My string will be always like:

Please message mpg of jazz 2014 and 2015+ to my mobile number +123456789

I have tried the following regex;

preg_match_all('!\d{4}+| \d{4}+\W!', $str, $matches);

This will output the following array.

Array
(
    [0] => Array
        (
            [0] =>  2015 
            [1] =>  2014+
            [2] => 1234
            [3] => 5678
        )

)

I need to get only the year portion with + symbol if any. I.e, i want only this:

Array
    (
        [0] => Array
            (
                [0] =>  2015 
                [1] =>  2014+                
            )

    )

回答1:


Your \d{4}+| \d{4}+\W pattern matches either 4 digits (note that the possessive {4}+ quantifier equals {4}) or a space, 4 digits, and any non-word char.

You may use

'~\b\d{4}\b\+?~'

See the regex demo

Details

  • \b - word boundary
  • \d{4} - 4 digits
  • \b - another word boundary
  • \+? - an optional (1 or 0 occurrences) plus symbols.

PHP demo:

$re = '~\b\d{4}\b\+?~';
$str = 'Please message mpg of jazz 2014 and 2015+ to my mobile number +123456789';
if (preg_match_all($re, $str, $matches)) {
    print_r($matches[0]);
}

Output:

Array
(
    [0] => 2014
    [1] => 2015+
)



回答2:


Matching dates (4 digits), optionally followed by a +, between spaces:

preg_match_all('( [0-9]{4}\+? )', $str, $matches);

echo '<pre>' . print_r($matches[0], true) . '</pre>';

Output:

Array
(
    [0] =>  2014 
    [1] =>  2015+ 
)


来源:https://stackoverflow.com/questions/51653030/extract-year-from-a-string-using-php-regex

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