Home >Backend Development >PHP Problem >How to filter string in php to only get numbers

How to filter string in php to only get numbers

青灯夜游
青灯夜游Original
2021-10-09 18:31:073394browse

Obtaining method: 1. Use the for statement to loop through the string, use the is_numeric() function in the loop body to extract the numeric characters and use the ".=" operator to splice them into a new string. 2. Use regular expressions and use the "preg_replace("/[^0-9]/", "", $str)" statement.

How to filter string in php to only get numbers

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

Method 1: Using is_numeric() Function

<?php
header("content-type:text/html;charset=utf-8");
function findNum($str) {
	$str = trim($str);
	if (empty($str)) {
		echo &#39;&#39;;
	}else{
		$result = &#39;&#39;;
		for ($i = 0; $i < strlen($str); $i++) {
			if (is_numeric($str[$i])) {
				$result .= $str[$i];
			}
		}
		echo $result;
	}
}
$str = &#39;0我是123456一段测试的字789符串0&#39;;
findNum($str);
?>
  • uses a for loop to traverse the string $str, and uses the is_numeric() function to determine whether $str[$i] is a numeric character. The is_numeric() function can detect whether a variable is a number or a numeric string.

  • Use is_numeric($str[$i]) in the loop body to determine whether the $str[$i] character is a numeric character; if so, take it out and use ".= ” spliced ​​into digital substrings.

Look at the output:

01234567890

Method 2: Use preg_replace() function

<?php
$str =&#39;0我是123456一段测试的字789符串0&#39;;
$result = preg_replace("/[^0-9]/", "", $str);
echo $result;
?>

How to filter string in php to only get numbers

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to filter string in php to only get 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