问题
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