Home > Blockchain >  PHP Regex year extraction no result [closed]
PHP Regex year extraction no result [closed]

Time:10-02

This does not output the year and I can not see why..

$string="On the 2015 @4.38am the fish being purchased is snapper"; 
preg_match("\b(19|20)\d\d\b",$string, $result);
preg_match("/[^ ]*$/", $string, $result2);
$year = $result[0];
$fishtype = $result2[0];
echo $year;
echo $fishtype;

CodePudding user response:

You can try and use the following regex for the year

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

Your code will be working with this

$string="On the 2015 @4.38am the fish being purchased is snapper"; 
preg_match("~\b\d{4}\b\ ?~",$string, $result);
preg_match("/[^ ]*$/", $string, $result2);
$year = $result[0];
$fishtype = $result2[0];
echo $year;
echo $fishtype;

Output

2015 Snapper
  • Related