php - get the first number in string if there is one

795

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.

672

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.

729

Answer

Solution:

If the number starts at begining you can do this like this:

$number = floatval($string); //it will return float e.g. 432

If you use comma instead of decimal point e.g. 43,123 you must first replace it with dot:

$string = str_replace(',', '.', '43,123 example');

People are also looking for solutions to the problem: php - What design pattern to use for a time-measurement profiler service?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.