Home  >  Article  >  Backend Development  >  How to get only numbers in php

How to get only numbers in php

藏色散人
藏色散人Original
2021-03-19 09:26:033243browse

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

Other methods for PHP to extract the numbers in the string

The first method uses regular expressions:

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

The second method, use the in_array method:

function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$temp=array('1','2','3','4','5','6','7','8','9','0');
$result='';
for($i=0;$i

The third method, use the is_numeric function:

function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$result='';
for($i=0;$i

[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!

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