How to extract all digits from a string in PHP?

In this article, To get the list of all numbers in a String, use the regular expression ‘[0-9]+’ with re.findall() method. [0-9] represents a regular expression to match a single digit in the string. [0-9]+ represents continuous digit sequences of any length.

1. Code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
function getAllDigitsInString($str) {
preg_match_all('!\d+!', $str, $matches);
return implode('', $matches[0]);
}
$str = "Soltuts.com1234 providing PHP tutorials, tips, tricks";
echo getAllDigitsInString($str);
?>
<?php function getAllDigitsInString($str) { preg_match_all('!\d+!', $str, $matches); return implode('', $matches[0]); } $str = "Soltuts.com1234 providing PHP tutorials, tips, tricks"; echo getAllDigitsInString($str); ?>
    <?php 
	
	function getAllDigitsInString($str) {
		preg_match_all('!\d+!', $str, $matches);
		return  implode('', $matches[0]);
	}
	$str = "Soltuts.com1234 providing PHP tutorials, tips, tricks";
	echo getAllDigitsInString($str);
    ?> 

2. Example:

Input:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
string input: "Soltuts.com1234 providing PHP 5tutorials, tips, tricks"
string input: "Soltuts.com1234 providing PHP 5tutorials, tips, tricks"
string input: "Soltuts.com1234 providing PHP 5tutorials, tips, tricks"

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
output: 12345
output: 12345
output: 12345