Since op asked for a short or best way. Number_from_string might perform better using a cast. Ignoring minus signs
(which could be hyphens in this example), we get a positive integer.
>>> $mrk = 'Science-80_John';
=> "Science-80_John"
>>> $num = (int)strpbrk ($mrk, "0123456789");
=> 80
The above use case assumes, besides only extracting one positive integer, that scientific notation
is OK. John has decided to be a clever lad and change his signature to a very large number. We'd have to decide under what circumstances the system should accept or reject scientific notation
.
>>> $mrk = 'Science-80E+21_John45';
>>> $num = (int)strpbrk ($mrk, "0123456789");
=> 9223372036854775807 // ack!
>>> $pat = "0123456789";
>>> $num = strpbrk ($mrk, $pat);
>>> $num = substr($num,0 ,strspn($num, $pat));
=> "80"
Since the new return value consists of digits, we don't strictly need the cast anymore because of PHP's type juggling. If there are no numbers at all, this solution returns the empty string, ""
which will generate an error if used in calculations later. Casting to (int)
would silently return 0
but not tell us if the database needs correction. Which would work better in this situation? Another design decision.
String functions also avoid potential pitfalls with regex in some solutions from Extract numbers from a string. What happens if there is an extra "45" in $str? The result, 8045
is probably not desirable.
>>> $mrk = 'Science-80_John45';
=> "Science-80_John45"
>>> $newStr = preg_replace("/\D+/", "", $mrk);
=> "8045"