Extract Floating Point Numbers from a Delimited String in PHP

Extract floating point numbers from a delimited string in PHP

$str = '152.15 x 12.34 x 11mm';
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);

The (?:...) regular expression construction is what's called a non-capturing group. What that means is that chunk isn't separately returned in part of the $mathces array. This isn't strictly necessary in this case but is a useful construction to know.

Note: calling floatval() on the elements isn't strictly necessary either as PHP will generally juggle the types correctly if you try and use them in an arithmetic operation or similar. It doesn't hurt though, particularly for only being a one liner.

Extract positive and negative floating point numbers from a string in php

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

This should do it for you.

$re = "/-?\\d+(?:\\.\\d+)?/m"; 
$str = "4.321 -3.1212";
$subst = "coach";

$result = preg_replace($re, $subst, $str);

In Php, how to get float value from a mixed string?

If you dont want to use regular expressions use filter_var:

$str = "CASH55.35inMyPocket";
var_dump( (float) filter_var( $str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) ); // float(55.35)

PHP, Regular expression to extract string to float number

Your regex is just searching for \d+. You are wanting to include decimal points (.) in your results.

You might want to try searching for \d[\d\.]* or similar to include the dot.

Extract a single (unsigned) integer from a string

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

PHP -How to extract prices with comma from text

Try this

echo preg_replace('([^\d,.]+)', '', '4,99 € Tax');

Result

4,99

This will replace anything that isnt a digit \d or period .

PHP preg_match_all to extract number with or without decimal

You should use this regex (add dot in character class) :

$matches = array();
$str = "I have string of 21.11 out of 30";
preg_match_all("/[\d\.]+/",$str,$matches);
var_dump($matches);

Test it (Ctrl + Enter)

How to extract a single letter or number from a string?

You can use a regEx to accomplish your goal as in this example

$myString = '<div id="craftysyntax_123" style="float: right;"><script type="text/javascript" src="https://livehelp.clipboards.com/livehelp_js.php?eo=0&department=1&serversession=1&pingtimes=10&dynamic=Y&creditline=W"></script></div>';
$pttn = '@craftysyntax_(\d{1,})@';
preg_match( $pttn, $myString, $matches );

echo '<pre>',print_r($matches,1),'</pre>';

This will output:

Array
(
[0] => craftysyntax_123
[1] => 123
)

so you can explicitly target the integer using $matches[1]



Related Topics



Leave a reply



Submit