How to get only numbers in php

藏色散人
Release: 2023-03-08 20:30:01
Original
3381 people have browsed it

php method to achieve only obtaining numbers: 1. Use the preg_match_all() function with regular expressions to obtain numbers, the syntax "preg_match_all('/(\d{3}(\.\d )?)/is ',$str,$result);"; 2. Define a string containing numbers from 0 to 9, traverse the array, and use the "in_array($str[$i],$temp)" statement to extract the numbers in the string; 3. Use the "is_numeric" function to get the number.

How to get only numbers in php

The operating environment of this article: windows7 system, PHP8 version, DELL G3 computer

PHP extracts the numbers in the string

PHP extracts the first group of numbers in the string

<?php
    $str=&#39;acc123nmnm4545&#39;;
    if(preg_match(&#39;/\d+/&#39;,$str,$arr)){
       echo $arr[0];
    }
?>
Copy after login

Other methods for PHP to extract the numbers in the string

The first method uses regular expressions:

function findNum($str=&#39;&#39;){
$str=trim($str);
if(empty($str)){return &#39;&#39;;}
$reg=&#39;/(\d{3}(\.\d+)?)/is&#39;;//匹配数字的正则表达式
preg_match_all($reg,$str,$result);
if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){
return $result[1][0];
}
return &#39;&#39;;
}
Copy after login

The second method, use the in_array method:

function findNum($str=&#39;&#39;){
$str=trim($str);
if(empty($str)){return &#39;&#39;;}
$temp=array(&#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;,&#39;0&#39;);
$result=&#39;&#39;;
for($i=0;$i<strlen($str);$i++){
if(in_array($str[$i],$temp)){
$result.=$str[$i];
}
}
return $result;
}
Copy after login

The third method, use the is_numeric function:

function findNum($str=&#39;&#39;){
$str=trim($str);
if(empty($str)){return &#39;&#39;;}
$result=&#39;&#39;;
for($i=0;$i<strlen($str);$i++){
if(is_numeric($str[$i])){
$result.=$str[$i];
}
}
return $result;
}
Copy after login

[Recommended: PHP video tutorial

The above is the detailed content of How to get 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template