I want to extract the numbers from a string that contains numbers and letters like:
"In My Cart : 11 items"
I want here to get the number 11
or any other number.
I want to extract the numbers from a string that contains numbers and letters like:
"In My Cart : 11 items"
I want here to get the number 11
or any other number.
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
$newstr = preg_replace('!\d+!', '', $str);
. It will strip out all the digits from your string. Example: $str = 'In My Cart : 11 12 items';
will output In My Cart : items
.
– Aether
Jun 8 '11 at 13:02
preg_replace("/[^0-9]/","",$string);
or filter_var($str, FILTER_SANITIZE_NUMBER_INT);
– eapo
Jul 21 '13 at 0:08
filter_var($str, FILTER_SANITIZE_NUMBER_INT);
extracted digits, plus and minus sign. The regex extracted only digits!
– PATROMO
Nov 9 '16 at 9:36
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);
xxx-yyy-24
you will get --24
. You can use str_repleace(array('+','-'), '', $result)
to delete both signs.
– imclickingmaniac
May 8 '13 at 9:09
max(0,filter_var($str, FILTER_SANITIZE_NUMBER_INT))
instead using arrays and string replacements.
– Eduard
May 24 '13 at 2:48
preg_replace('/[^0-9]/', '', $string);
This should do better job!...
500.00
will print : 50000
– ErickBest
Jul 22 '13 at 10:10
extract the numbers from a string
-- a decimal point is not a number!
– rybo111
Feb 1 '14 at 17:30
'
and not double quotes "
.
– CommandZ
Apr 7 '15 at 18:14
Using preg_replace
:
$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;
Output: 1111111111
+387 (61) 634-783
string to 38761634783
directly. You don't have to take care of arrays like Gaurav's answer.
– beytarovski
Jul 2 '16 at 13:13
For floating numbers,
preg_match_all('!\d+\.*\d*!', $string ,$match);
See my comment for the updated regex.
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:
php - regex - how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01)?
Using preg_replace
$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;
You can use following function:
function extract_numbers($string)
{
preg_match_all('/([\d]+)/', $string, $match);
return $match[0];
}
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
try this,use preg_replace
$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
$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
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
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");
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);
One of the simple method I found without using regex for begineers was:
$string= "21321&*^&*^das";
$splitted=str_split($string);
foreach ($splitted as $char){
if($char%1!=$char){
echo " ".$char;
}
}
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 )
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
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)
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.
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;
}