Mons
Mons

Reputation: 36

Find words from the array in the text received through file_get_contents

I have a receipt of a remote page:

$page = file_get_contents ('http://sayt.ru/');

There is a array of words:

$word = array ("word", "second");

How to count the number of words in the array matches the text on the page? Started to dig in the direction

$matches = array ();
$count_words = preg_match_all ('/'. $word. '/ i',$page, $matches);

But certainly not in the direction I dig because count is always zero. And through preg_match_all sought after one word, not the entire array. : (

Upvotes: 1

Views: 176

Answers (1)

dev-null-dweller
dev-null-dweller

Reputation: 29462

you have to either check or each word in array or use regexp like this:

$serachWords = array_map(function($w){ return preg_quote($w,'/'); }, $word);
$search = implode('|', $searchWords);
$count_words = preg_match_all('/\b(?:'.$serach.')\b/i', $page, $matches);

Added few modification to have better results: escape all words, so they wouldn't break expression and add word boundaries (\b) no match word as a word, not part of swords.

Upvotes: 3

Related Questions