How to implement the function of taking only numbers in php

藏色散人
Release: 2023-03-02 06:18:02
Original
5392 people have browsed it

How to implement php to only take numbers: 1. Use the "preg_match" function to extract numbers from the string; 2. Use PHP's built-in "in_array" method to extract all the numbers that appear in the string. And spliced together; 3. Use the "is_numeric" method.

How to implement the function of taking only numbers in php

php Extract numbers from the string

1. Regular extraction [Only extract the first occurrence Numbers]

Copy after login

2. Regular extraction [All numbers appearing in the string are extracted in array form]

Copy after login

3. Use in_array Method [Extract all the numbers that appear in the string and splice them together in string form] Pay attention to the encoding issue

$str='我是123456一段测试的字789符串00'; $str=trim($str); if (!empty($str)) { $key = ['0','1','2','3','4','5','6','7','8','9']; $number = ''; for ($i = 0;$i < strlen($str);$i++) { if (in_array($str[$i],$key)){ $number .= $str[$i]; } } } print_r($number);
Copy after login

4. Use the is_numeric method like the in_array method

The above is the detailed content of How to implement the function of taking only numbers in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!