Home  >  Article  >  Backend Development  >  How to implement the function of taking only numbers in php

How to implement the function of taking only numbers in php

藏色散人
藏色散人Original
2020-07-06 11:20:545470browse

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]

<?php
$str =&#39;我是123456一段测试的字789符串00&#39;;
preg_match(&#39;/\d+/&#39;,$str,$number);
print_r($number);
?>

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

<?php
$str =&#39;我是123456一段测试的字789符串00&#39;;
preg_match_all(&#39;/\d+/&#39;,$str,$arr);
print_r($arr);
?>

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=&#39;我是123456一段测试的字789符串00&#39;;
$str=trim($str);
if (!empty($str)) {
    $key    = [&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;];
    $number = &#39;&#39;;
    for ($i = 0;$i < strlen($str);$i++) {
        if (in_array($str[$i],$key)){
            $number .= $str[$i];
        }
    }
}
print_r($number);

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!

Statement:
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