I went with the following solution. Uppercase "D" stands for "non-digit".
public static function sanitize_integer($str)
{
return (int) preg_replace('/\D/', '', $str);
}
If your input string may have leading zeros that you wish to retain, do not cast the mutated string as an integer.
return preg_replace('/\D/', '', $str);
To make fewer replacements (but the same result), use the +
(one or more quantifier) to remove multiple consecutive non-numeric characters during each replacement.
return preg_replace('/\D+/', '', $str);