简体   繁体   中英

PHP File Handling hw

$handle = fopen("mytext.txt", "r");

echo fread($handle,filesize("mytext.txt"));
echo preg_match("/[0-9]/","",$handle);

fclose($handle);

I want to open a text file and find how many digits are there in the text. I tried to use preg_match but I think this is not correct way to do it.

preg_match() accepts Handle for resources. Which is incorrect:

$handle = fopen("mytext.txt", "r");

$content = fread($handle,filesize("mytext.txt"));
$noDigit = preg_match("/[0-9]/","",$content);

fclose($handle);

You should be using preg_match_all() . preg_match() will only match the first result.

Also, your regex is looking for a single numeric value. You should use \\d+ to match all instances of one or more numbers (ie matches 1, 20, and 3580243).

$subject = "String with numbers 4 8 15 16 23 42";
$matches = array();
preg_match_all('\d+', $subject, $matches);

Then, to count them, you can just loop through the matches in $matches and increment a counter variable.

EDIT: Also, you'd probably get better results with file_get_contents() instead of using fopen, fread, fclose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM