I am trying to remove certain parts of my string using preg_match
. I do not know if this is the best scenario.
I have the following string:
Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt
I want to get only the 117.09
part of the string. I am using preg_match
like this:
$res = preg_replace("/[^0-9]/", "", $string);
But this will return all the numbers found in the string, so I would have something like:
131111709
Any help would be greatly appreciated. Thank you and happy holidays.
You should be using a matching approach rather than the replacing one.
Use
/([\d.]+)\s*MiB/
Or, if the Size
word is always before the number, then use
/Size\s*([\d.]+)/
and grab Group 1 value. See the regex demo (or this demo).
Pattern details:
([\d.]+)
- Group 1 capturing 1 or more digits or .
\s*
- 0+ whitespacesMiB
- a sequence of literal chars.NOTE that you may make the number matching part more precise by replacing [\d.]+
with \d*\.?\d+
.
$re = '/([\d.]+)\s*MiB/';
$str = 'Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt';
if (preg_match($re, $str, $match)) {
echo $match[1]; // => 117.09
}
You can get it by following regex:
$re = '/(?<=Size )(\d.)+/';
$str = 'Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt';
if (preg_match($re, $str, $match)) {
echo $match[0]; // => 117.09
}
You can try this also -
$s = 'Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt';
preg_match('/\d*\.\d*/', $s, $match);
var_dump($match[0]);
Output
string(6) "117.09"
\d* matches a digit (equal to [0-9])
@Cristian Badea if you want to extract particular part of string like 117.09 from your string so you can also get this by the php string function
try the below strpos, substr function to get your 117.09 string from the whole string
<?php
$a = "Uploaded Today 13:11, Size 117.09 MiB, ULed by demonoidt";
$extract = "117.09";
if(strpos($a, $extract)){
$b = substr($a, strpos($a, $extract), strlen($extract));
echo $b;
}
?>
In $b you will get your 117.09 part of string (y)