Home > Backend Development > PHP Tutorial > How Can I Extract Whole Numbers from a String in PHP?

How Can I Extract Whole Numbers from a String in PHP?

DDD
Release: 2024-12-25 10:28:11
Original
127 people have browsed it

How Can I Extract Whole Numbers from a String in PHP?

Isolating Whole Numbers Within a Textual String

Extracting integers from a string that contains both numerical and alphabetical characters can be a common task. For instance, you may encounter a situation where you need to extract the number 11 from a string such as "In My Cart : 11 items."

Using Filter_Var for Integer Extraction

To isolate the digits without fuss, the filter_var function offers a convenient solution. This function allows you to sanitize user input and extract numeric data. Let's see an example using filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
Copy after login

In this example, we assign the string to the $str variable. Next, we call filter_var, providing $str as the input and FILTER_SANITIZE_NUMBER_INT as the filter type. This filter removes all non-numeric characters from the string, effectively isolating the integer 11.

Finally, we cast the result to an integer using (int), ensuring it is represented as a numerical value. The value assigned to $int will be 11. This method is straightforward and efficient for extracting whole numbers from textual strings.

The above is the detailed content of How Can I Extract Whole Numbers from a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template