سؤال

I want to extract both decimal numbers and integers in a string. I am in halfway.

My code is:

$str = 'In My Cart : +11 -12 4577 012 4.5 9 +0.1 -4.9 345.876 0 items';
print_r($str);
echo "</br>";
preg_match_all('!\+*\-*(\d+)!', $str, $matches);
print_r($matches);

It returns integers correctly but it splits decimal values into two values. Also, my output returns in array(array()) format instead of just array().

How can I also extract decimal values correctly and output in array() format?

Output:

User Input: In My Cart : +11 -12 4577 012 4.5 9 +0.1 -4.9 345.876 0 items Array ( [0] => Array ( [0] => +11 [1] => -12 [2] => 4577 [3] => 012 [4] => 4 [5] => 5 [6] => 9 [7] => +0 [8] => 1 [9] => -4 [10] => 9 [11] => 345 [12] => 876 [13] => 0 ) [1] => Array ( [0] => 11 [1] => 12 [2] => 4577 [3] => 012 [4] => 4 [5] => 5 [6] => 9 [7] => 0 [8] => 1 [9] => 4 [10] => 9 [11] => 345 [12] => 876 [13] => 0 ) ) 

هل كانت مفيدة؟

المحلول

Use this regex:

([+-]?\d+(?:\.\d+)?)

The number (integer or float) will be in group 1.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top