Am I using preg_replace (PHP) correctly?

I think I have this right, but I would like someone to confirm this.

function storageAmmount()
{
    system('stat /web/'.$user."/ | grep Size: > /web/".$user."/log/storage");
    $storage = fopen('/web/'.$user.'/log/storage');
    $storage = str_replace('Size:', " ", $storage);
    $storage = preg_replace('Blocks:(((A-Z), a-z), 1-9)','',$storage);
}

This is the line in the text file:

Size: 4096       Blocks: 8          IO            Block: 4096   directory

I try to get only a numerical value: "Size:", the word "Size" and everything else is useless to me.

I mostly look at preg_replace. Is it just me or regular, a little confusing? Any suggestions. Thanks for any help in advance.

Hooray!

Phill


Good,

Here's what the function looks like now:

function storageAmmount()
{
$storage = filesize('/web/'.$user.'/');
$final = $storage/(1024*1024*1024);
return $final;
}

Wherever I put number_format (), I'm not sure if it will go in the equation or in the return statement. I got it in both cases when it returns "0.00".

V1.

function storageAmmount()
{
$storage = filesize('/web/'.$user.'/');
$final = number_format($storage/(1024*1024*1024), 2);
return $final;
}

or v2.

function storageAmmount()
{
$storage = filesize('/web/'.$user.'/');
$final = $storage/(1024*1024*1024);
return number_format($final, 2);
}

do not work, and both of them return "0.00". Any thoughts?

+3
source share
5

, . , filesize PHP, .

function storageAmmount(){    
    $storage = filesize('/web/'.$user);
}
+3

, preg_replace .

; , , Regex. . : http://www.regular-expressions.info/

, str_replace preg_replace , preg_match.

- :

$matches = preg_match('/Size: (\d+)/',$storage);
$storage = $matches[1];

(\d+) $matches. Size: , Size: .

, , - preg_; explode() . .

+2

// preg_match solution    
$storage = 'Size: 4096 Blocks: 8 IO Block: 4096 directory';
if (preg_match('/Size: (?P<size>\d+)/', $storage, $matches)) {
    return matches['size'];
}

, php stat

// php stat solution
$f = escapeshellcmd($user);
if ($stat = @stat('/web/'.$f.'/log/storage')) {
    return $stat['size'];
}
+2

, ( , - ), , .

, explode:

function storageAmount($user) {
    system(escapeshellcmd('stat /web/'.$user.'/ | grep Size: > /web/'.$user.'/log/storage'));
    $storageChunks = explode(' ', file_get_contents('/web/'.$user.'/log/storage'));
    return $storageChunks[1];
}

:

+1
source

You tried

$storage = preg_replace('Block:.*','',$storage)

?

It would be even better to use

 function storageAmmount()
 {
   exec('stat /web/'.$user.'/ | grep Size:',$output);
   preg_match("/Size: ([0-9]*).*/",$output[0],$matches);
   return $matches[1];
 }

(tested on my machine)

0
source

Source: https://habr.com/ru/post/1783848/


All Articles