Extract a single (unsigned) integer from a string

PhpStringIntegerText Extraction

Php Problem Overview


I want to extract the digits from a string that contains numbers and letters like:

"In My Cart : 11 items"

I want to extract the number 11.

Php Solutions


Solution 1 - Php

If you just want to filter everything other than the numbers out, the easiest is to use filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

Solution 2 - Php

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

Solution 3 - Php

preg_replace('/[^0-9]/', '', $string);

This should do better job!...

Solution 4 - Php

Using preg_replace:

$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;

Output: 1111111111

Solution 5 - Php

For floating numbers,

preg_match_all('!\d+\.?\d+!', $string ,$match);

Thanks for pointing out the mistake. @mickmackusa

Solution 6 - Php

I do not own the credit for this, but I just have to share it. This regex will get numbers from a string, including decimal points/places, as well as commas:

/((?:[0-9]+,)*[0-9]+(?:\.[0-9]+)?)/

Cited from here:
https://stackoverflow.com/questions/14482022/php-regex-how-to-extract-a-number-with-decimal-dot-and-comma-from-a-string#answer-14482071

Solution 7 - Php

You can use preg_match:

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);

Solution 8 - Php

Using preg_replace

$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;

Solution 9 - Php

$value = '25%';

Or

$value = '25.025$';

Or

$value = 'I am numeric 25';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

This will return only the numeric value

Solution 10 - Php

You can use following function:

function extract_numbers($string)
{
   preg_match_all('/([\d]+)/', $string, $match);
 
   return $match[0];
}

Solution 11 - Php

The top resource-friendly solutions

<?php
	var $string = "In My Cart : 11 items";
?>
1. Fastest: filter_varFilters a variable with a specified filter
<?php
	filter_var($string, FILTER_SANITIZE_NUMBER_INT); // string(2) "11"
?>
2. Almost the fastest: str_replace — Replace all occurrences of the search string with the replacement string
<?php
	str_replace(array('In My Cart : ',' item', 's'),"", $string); // string(2) "11"
?>
3. Fast enough: preg_replacePerform a regular expression search and replace
<?php
	preg_replace("/[^0-9]/","",$string); // string(2) "11"
?>
However
  • the simplicity of str_replace cause speed, but even limited use cases

  • preg_replace is much more versatile than str_replace or filter_var

  • instead is possible to use a function to specify what to replace using preg_replace_callback

  • with preg_replace_callback can do multiple replacements in one call

  • filter_var limited in sanitation options

Solution 12 - Php

preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

Solution 13 - Php

try this,use preg_replace

$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;

DEMO

Solution 14 - Php

we can extract int from it like

$string = 'In My Car_Price : 50660.00';

echo intval(preg_replace('/[^0-9.]/','',$string));  # without number format   output: 50660
echo number_format(intval(preg_replace('/[^0-9.]/','',$string)));  # with number format  output :50,660

demo : http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398

Solution 15 - Php

Follow this step it will convert string to number

$value = '$0025.123';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
settype($onlyNumeric,"float");

$result=($onlyNumeric+100);
echo $result;

Another way to do it :

$res = preg_replace("/[^0-9.]/", "", "$15645623.095605659");

Solution 16 - Php

Since there is only 1 numeric value to isolate in your string, I would endorse and personally use filter_var() with FILTER_SANITIZE_NUMBER_INT.

echo filter_var($string, FILTER_SANITIZE_NUMBER_INT);

A whackier technique which works because there is only 1 numeric value AND the only characters that come before the integer are alphanumeric, colon, or spaces is to use ltrim() with a character mask then cast the remaining string as an integer.

Demo

$string = "In My Cart : 11 items";
echo (int)ltrim($string, 'A..z: ');
// 11

If for some reason there was more than one integer value and you wanted to grab the first one, then regex would be a direct technique.

Demo

echo preg_match('/\d+/', $string, $m) ? $m[0] : '';

sscanf() is rather handy if you need to explicitly cast the numeric string as an integer (or float). If it is possible/unknown for the integer value to occur at the start of the string, then prepend a non-numeric character to the input string before scanning it. The following technique matches leading non-digits (and ignores them with * after the %), then matches the first occurring sequence of digits and casts the returned substring as an integer.

Demo

var_dump(sscanf(' ' . $string, '%*[^0-9]%d')[0]);

To adapt this technique to extract a float value, just change the d to f. For more information on the (currently undocumented) assignment suppression feature of sscanf(), see this post.

Solution 17 - Php

other way(unicode string even):

$res = array();
$str = 'test 1234 555 2.7 string ..... 2.2 3.3';
$str = preg_replace("/[^0-9\.]/", " ", $str);
$str = trim(preg_replace('/\s+/u', ' ', $str));
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++) {
    if (is_numeric($arr[$i])) {
        $res[] = $arr[$i];
    }
}
print_r($res); //Array ( [0] => 1234 [1] => 555 [2] => 2.7 [3] => 2.2 [4] => 3.3 ) 

Solution 18 - Php

An alternative solution with sscanf:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');

Solution 19 - Php

Depending on your use case, this might also be an option:

$str = 'In My Cart : 11 items';
$num = '';

for ($i = 0; $i < strlen($str); $i++) {

    if (is_numeric($str[$i])) {
        $num .= $str[$i];
    }
}

echo $num; // 11

Though I'd agree a regex or filter_var() would be more useful in the stated case.

Solution 20 - Php

for utf8 str:

function unicodeStrDigits($str) {
    $arr = array();
    $sub = '';
    for ($i = 0; $i < strlen($str); $i++) { 
        if (is_numeric($str[$i])) {
            $sub .= $str[$i];
            continue;
        } else {
            if ($sub) {
                array_push($arr, $sub);
                $sub = '';
            }
        }
    }

    if ($sub) {
        array_push($arr, $sub); 
    }
    
    return $arr;
}

Solution 21 - Php

> If you don't know which format the number is? int or floating, then use this :

$string = '$125.22';

$string2 = '$125';

preg_match_all('/(\d+.?\d+)/',$string,$matches); // $matches[1] = 125.22

preg_match_all('/(\d+.?\d+)/',$string2,$matches); // $matches[1] = 125

Solution 22 - Php

This functions will also handle the floating numbers

$str = "Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4";
$str = preg_replace('/[^0-9\.]/','-', $str);
$str = preg_replace('/(\-+)(\.\.+)/','-', $str);
$str = trim($str, '-');
$arr = explode('-', $str);

Solution 23 - Php

This script creates a file at first , write numbers to a line and changes to a next line if gets a character other than number. At last, again it sorts out the numbers to a list.

string1 = "hello my name 12 is after 198765436281094and14 and 124de"
f= open("created_file.txt","w+")
for a in string1:
    if a in ['1','2','3','4','5','6','7','8','9','0']:
	    f.write(a)
    else:
	    f.write("\n" +a+ "\n")
f.close()


#desired_numbers=[x for x in open("created_file.txt")]

#print(desired_numbers)

k=open("created_file.txt","r")
desired_numbers=[]
for x in k:
    l=x.rstrip()
    print(len(l))
    if len(l)==15:
	    desired_numbers.append(l)


#desired_numbers=[x for x in k if len(x)==16]
print(desired_numbers)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAhmed Ala DaliView Question on Stackoverflow
Solution 1 - PhpDaniel BøndergaardView Answer on Stackoverflow
Solution 2 - PhpGauravView Answer on Stackoverflow
Solution 3 - PhpMahipalsinh RavaljiView Answer on Stackoverflow
Solution 4 - PhpAkash DeepView Answer on Stackoverflow
Solution 5 - PhpYashView Answer on Stackoverflow
Solution 6 - PhpmroncetwiceView Answer on Stackoverflow
Solution 7 - PhpDmitri GudkovView Answer on Stackoverflow
Solution 8 - PhpHariadiView Answer on Stackoverflow
Solution 9 - PhpRakeshView Answer on Stackoverflow
Solution 10 - PhpJasmeenView Answer on Stackoverflow
Solution 11 - PhpeapoView Answer on Stackoverflow
Solution 12 - PhpBradley KovacsView Answer on Stackoverflow
Solution 13 - PhpDaveView Answer on Stackoverflow
Solution 14 - Phpuser889030View Answer on Stackoverflow
Solution 15 - PhpjewelhuqView Answer on Stackoverflow
Solution 16 - PhpmickmackusaView Answer on Stackoverflow
Solution 17 - PhpMehrdadView Answer on Stackoverflow
Solution 18 - PhpFrancesco TerenzaniView Answer on Stackoverflow
Solution 19 - PhpkasimirView Answer on Stackoverflow
Solution 20 - PhpMehrdadView Answer on Stackoverflow
Solution 21 - PhpSajjad Hossain SagorView Answer on Stackoverflow
Solution 22 - PhpKhaldoon MasudView Answer on Stackoverflow
Solution 23 - PhpAbhishek PoudelView Answer on Stackoverflow