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.
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 ''; }else{ $result = ''; for ($i = 0; $i < strlen($str); $i++) { if (is_numeric($str[$i])) { $result .= $str[$i]; } } echo $result; } } $str = '0我是123456一段测试的字789符串0'; 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 ='0我是123456一段测试的字789符串0'; $result = preg_replace("/[^0-9]/", "", $str); echo $result; ?>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
