如何从特殊字符串中获取数字? PHP

For example, 3 string are the following :

@@7##

@@563##

@@120058##

How can I get those number like this :

echo first number is 7

echo second number is 563

echo third number is 120058

Thank you very much!

$numberAsString = trim($string, '@#')

Is probably the easiest and fastest in this case. The output is still a string in this case, but in most cases that doesn't really matter. If it does in your case, you can use (int), (float) or the like to get it to the correct type.

Of course, regex would also be possible, e.g.:

$didMatch = preg_match('/@+([^#]+)#+/', $string, $matches);

Another possibility still is first extract the remaining part after the initial 2 @ and then cast to a number, which seems to be always int in this case:

$number = (int)substr($string, 2);

Still another possibility would be to go by the count of the characters and just use substr like:

$numberAsString = substr($string, 2, -2);

Or you could be creative and use something like explode + implode + array functions:

$numberAsString = array_slice(explode('#', implode('', array_slice(explode('@', $string), 2))), 0, -2);

Of course, this last one is purely to show that it can be done in various ways, as it's very inefficient and impractical, but there are surely dozens of other ways.

In case you use this in a tight loop or somewhere where performance really matters, I would benchmark different possibilities - on a guess, I'd say that either the trim or the pure substring solution would be the fastest.

$str = "@@563##";
preg_match("|\d+|", $str, $res);
print_r($res);

Just call the filter_var() function it will return the number only.

Whatever the input is, it will only filter the number for you!

    filter_var("@@120058##", FILTER_SANITIZE_NUMBER_INT) // return 120058
    filter_var("*##20kkk", FILTER_SANITIZE_NUMBER_INT) // return 20