6

I'm looking for a function that counts the number of times a string occurs within a file, I tried using $count = preg_match_all("/String/", $file, $matches); but it returns Warning: preg_match_all() expects parameter 2 to be string, resource given. Is there any function that allows me to do this with a file, instead of a string, or is there any way to assign a file to a string (I assume the latter would be a lot slower)?

1
  • 1
    You need to pass a string value to the 2nd parameter. Perhaps you can do: file_get_contents($filename) for that argument. Commented May 23, 2011 at 23:16

2 Answers 2

12

yes:

file_get_contents() — Reads entire file into a string

http://php.net/manual/en/function.file-get-contents.php

so for you it would be

$file = file_get_contents(PATH_TO_FILE);
$count = preg_match_all("/String/", $file, $matches);

I'm guessing you have used fopen instead by mistake?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I've been using fopen, but file_get_contents is exactly what I needed. Thank you.
9
$count = substr_count(file_get_contents($file), $string);

Manual:
substr_count
file_get_contents

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.