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
43 432 432 43 43,123
I assume it would be possible to use
strpos 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.
With a regex, you can extract numbers from a string.
The following statement should do the trick:
preg_match_all('~\d+~', $string, $match);
$matchis the array of the numbers contained in
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: