Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out numbers in a string in php

Tags:

php

assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .

like image 923
Rami Dabain Avatar asked Jan 29 '11 14:01

Rami Dabain


2 Answers

$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);

// $number = (int) $str;
like image 187
Tim Cooper Avatar answered Sep 23 '22 19:09

Tim Cooper


Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.

filter_var

flags for the filters

e.g. to get just numbers from the given string

<?php
$a = '!a-b.c3@j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>

To adhere to more strict standards for your question, I have updated my answer to give a better result.

I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.

Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.

Edit:

1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT

2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].

like image 43
Abhishek Madhani Avatar answered Sep 23 '22 19:09

Abhishek Madhani