Home  >  Article  >  Backend Development  >  How to implement PHP to only retain numbers?

How to implement PHP to only retain numbers?

Guanhui
GuanhuiOriginal
2020-07-23 11:11:015265browse

How to implement PHP to only retain numbers?

#How to implement PHP to only retain numbers?

1. Use regular expressions to match all numbers and extract them, or replace characters that are not numbers;

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

2. Split the string into an array and traverse it The array determines whether each character is a number, and if so, it can be extracted.

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;
}
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;
}

Recommended tutorial: "PHP"

The above is the detailed content of How to implement PHP to only retain numbers?. 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