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 nu
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)
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);
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 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);
$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
Using preg_replace
$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;