Frank Nwoko
Frank Nwoko

Reputation: 3934

Get keywords from a string or group of strings

Is there a way to extract keywords from a string?

Eg. string = "Obi goes to school"

How can keywords like "school" or Obi be extracted from the string.

Platform is php/mysql

Upvotes: 0

Views: 869

Answers (3)

Rafe Kettler
Rafe Kettler

Reputation: 76955

If you're trying to get a specific word

There are many common string methods (reference is here) that do some variation of this task. The most simple would be strpos(), which finds the position of the first occurrence of a string in a larger string.

$str = "Obi goes to school";
$school_pos = strpos($str, "school");

You can also look into regular expressions if you need to match more complex patterns.

If you're trying to just get a list of words in general

In this case, $word_array = explode(' ', $some_str); works like a charm.

Upvotes: 2

Nick Anderegg
Nick Anderegg

Reputation: 1016

If you don't already know what the string is going to be and you want to do something with the various tokens that you can extract from the string, you could always try explode().

<?php
     $string = "Here are my tokens.";
     $tokens = explode(" ", $string);
?>

And so echo $tokens[0]; would print Here, echo $tokens[2]; would print my, etc.

If you just want to find a specific word, use strpos().

<?php
     $string = "Here is my string.";
     $keyword = "is";
     $pos = strpos($keyword, $string);
     echo $pos; // This would print 5.
?>

Upvotes: 0

profitphp
profitphp

Reputation: 8354

$strings = explode (' ','Obi goes to school');

That will separate them out into an array. If by keywords you meant nouns, then get a dictionary file that shows parts of speech, then loop through the array of strings and determine if each entry is a noun using the dictionary. Which will obviously be quirky, language is a tough thing to program reliably.

Upvotes: 1

Related Questions