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!