0

How can you use substr_count to count each element in an array's occurance in another array?

i.e. $urls = array (
'www.thesun.co.uk',
'www.bbcnews.co.uk',
);

$names = array (
'rex kum',
'tony blair', 
);

so if i wanted to use substr_count to count the occurance of the name rex kumi on the sun webpage, how would this work?

2 Answers 2

1

If you're going to do this a lot I'd put it in a function but:

 foreach($names as $name)
 {
       foreach($urls as $url)
      {
           print "Count for $name and $url is: " . substr_count($url, $name);
      }
 }

The question that you asked (counting the instances of one array in another array) is different from what you actually asked (count the instances of one array, on a web site). You actually want a combination of my answer and the answer mentioned where you load the contents of the website. (Use nested foreach loops)

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

Comments

0

It looks you're missing the php basics, but what the hack. You'll use function nested foreach loop:

$results = array();
foreach( $urls as $url){
    foreach( $names as $key => $name){
        if( !isset( $results[$key])){
           $results[$key] = 0; // you better initialize elements in separate foreach loop
        }

        // Strtolower because name may be capitalized, uppercased and so on
        $content = strtolower( file_get_contents( $url));
        $results[$key] += substr_count( $content, strtolower( $name));
    }
}

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.