How to extract a single unsigned integer from a string with PHP?

Spread the love

Sometimes, we want to extract a single unsigned integer from a string with PHP.

In this article, we’ll look at how to extract a single unsigned integer from a string with PHP.

How to extract a single unsigned integer from a string with PHP?

To extract a single unsigned integer from a string with PHP, we can call filter_var with FILTER_SANITIZE_NUMBER_INT.

For instance, we write

$str = 'In My Cart: 100 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

to extract 100 from $str by calling filter_var with $str and FILTER_SANITIZE_NUMBER_INT.

And then we convert the returned string to an integer with int.

Conclusion

To extract a single unsigned integer from a string with PHP, we can call filter_var with FILTER_SANITIZE_NUMBER_INT.

Leave a Reply

Your email address will not be published.