How to filter string in php to only get numbers

青灯夜游
Release: 2023-03-13 08:30:02
Original
3351 people have browsed it

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);
?>
Copy after login
  • 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
Copy after login

Method 2: Use preg_replace() function

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!