0

I'm trying to pull out certain groups of keywords from a block of text using substr_count and have it count how many times the words in each group appears.

I've created an array called $keywords, within it is another set of arrays which contain the actual keywords I am looking for.

This is my current code:

$textDump = "random bunch of text";

$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
foreach ($keywords as $item){
    foreach ($item as $newItem){
        $number += substr_count(strtolower($textDump), strtolower($newItem));
        echo $number;
    };
};

My problem is that it counts all the keywords within all the arrays and adds everything together, what I want is just the total for each group of keywords. Any ideas on what I should do?

3 Answers 3

3
$keywords = array("sports"=>$keyWordsSports, "tech"=>$keyWordsTech);
$count=array("sports"=>0,"tech"=>0);
foreach ($keywords as $key=>$item){
    foreach ($item as $newItem){
        $count[$key] += substr_count(strtolower($textDump), strtolower($newItem));
    }
}
print_r($count);

Edit: Live example

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

Comments

1

Try this :

$textDump = "raptor bunch raptor basektball";

$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
$matches=array();
foreach ($keywords as $item){
    foreach ($item as $newItem){
        $number = substr_count(strtolower($textDump), strtolower($newItem));
        if($number>0)
        {
        $matches[strtolower($newItem)]=$number;
        }
    };
};
print_r($matches);

Comments

0

you just need to echo the $number outside the inner foreach like this,

$textDump = "random bunch of text";
$keyWordsSports = array("nba", "raptor", "ufc", "basektball", "gym", "mma", "realgm", "running");
$keyWordsTech = array("apple", "rim", "blackberry", "facebook", "twitter", "google" );
$keywords = array($keyWordsSports, $keyWordsTech);
foreach ($keywords as $item) {
    foreach ($item as $newItem) {
        $number += substr_count(strtolower($textDump), strtolower($newItem));
    }
    echo $number;
}

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.