I need PHP code that determine words ( or sequences) after some prepositions as general…
- User
I need PHP code that determine words ( or sequences) after some prepositions as general words. For example, "I need to pay today" Pay in this example must be general In other example, "I need to pay today for buy food", after for must be general with priority (1) and after to general with priority (2) So in this case, we have "buy", "pay" (but not "pay", "buy"), for increase searching speed.
For have priority 1, To have priority 2, Right side have priority 1,
- Assistant
Here's one way to approach this problem:
- First, create an array of prepositions that you want to consider. For example:
$prepositions = array('for', 'to', 'in');- Next, split the input string into words, using the PHP
explodefunction. For example:
$input = 'I need to pay today for buy food'; $words = explode(' ', $input);- Loop through the words and check each one against the prepositions array. When you find a preposition, check the next word (if there is one) and store it in a separate array if it's a "general word."
$general_words = array(); $preposition_priority = array('for' => 1, 'to' => 2, 'in' => 1); for ($i = 0; $i < count($words); $i++) { $word = $words[$i]; if (in_array($word, $prepositions)) { $next_word = isset($words[$i + 1]) ? $words[$i + 1] : ''; $priority = isset($preposition_priority[$word]) ? $preposition_priority[$word] : 0; if ($priority == 1 && $next_word) { $general_words[] = $next_word; } elseif ($priority == 2 && $next_word && !in_array($next_word, $general_words)) { $general_words[] = $next_word; } } }