PHP Tip: Use of Regular Expression to stripe off string part.

Tips-And-Tricks

Use of regular Expression to stripe off string part from Age (e.g, 10/10y/10 y/10year/10 year/10 years) in PHP.

$age = "30 years";
//$age = "30";
//$age = "30y";
if ( preg_match("/(\d)(\s)(\D*)/i", $age, $match)){
if( is_numeric($match[1]) )
$age_num = $match[1];
}

echo $age_num;

The output will be 30.