php - get the first number in string if there is one
I am looking for a way to extract the first number out of a string. This examples
43
432Phill 21
432hill 21
43#1 Example
43,123 example
should return
43
432
432
43
43,123
I assume it would be possible to usestrpos
and iterate needle from a-z, A-Z and #. to get all positions and than use the lowest non-zero one to determine the point where number ends. This seems like an overkill. Is there a better way of doing it ?
EDIT: the position is to use substr later. If there is a better way I am down with it.
Answer
Solution:
With a regex, you can extract numbers from a string.
The following statement should do the trick:
preg_match_all('~\d+~', $string, $match);
$match
is the array of the numbers contained in$string
.Answer
Solution:
If the number starts at begining you can do this like this:
If you use comma instead of decimal point e.g. 43,123 you must first replace it with dot: