1

Am using the str_word_count() to count how many times a word appears in a text but what i really want is to count only specific words starting and ending with '[word here]'

$text = "Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.";

$words = str_word_count($text, 1); 
$frequency = array_count_values($words);
arsort($frequency);
echo '<pre>';
print_r($frequency);
echo '</pre>';

Output:

Array
(
    [required] => 1
    [field] => 1
    [graduate] => 1
    [degree] => 1
    [preferred] => 1
    [KM-relevant] => 1
    [other] => 1
    [binb] => 1
    ['Information-Systems'] => 1
    ['Computer-Science'] => 1
    [or] => 1
    [Degree] => 1
)
Rizier123
  • 58,877
  • 16
  • 101
  • 156
Unsung
  • 23
  • 3

3 Answers3

1

To find all words in single quotes, use a regular expression with preg_match_all():

$text = "Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.";

preg_match_all("/'([^']+)'/", $text, $matches);

var_dump($matches[1]);
echo "Found " . count($matches[1]) . " matches." . PHP_EOL;

This will output:

array(2) {
  [0] =>
  string(19) "Information-Systems"
  [1] =>
  string(16) "Computer-Science"
}
Found 2 matches.
jeromegamez
  • 3,348
  • 1
  • 23
  • 36
0

Use substr() to check is begining/end of string equal to some other string, you are searching for:

http://php.net/manual/en/function.substr.php

As you can notice there, if you want to compare from end of string use negative $start value.

For length paramater use strlen() to get string length:

http://php.net/manual/en/function.strlen.php

MilanG
  • 6,994
  • 2
  • 35
  • 64
0

PHP pseudo-code example:

function find_words_prefix($text, $prefix)
{
  $words = array_filter(explode(' ', $text), 'strlen'); // get only non-emoty words
  $prefixed_words = array();
  $prefix_len = strlen($prefix);
 foreach ($words as $word)
{
if (strlen($word) < $prefix_len) continue; // no use testing this word as it is smaller than prefix
if ( 0 === strpos($word, $prefix) ) $prefixed_words[] = $word;
}
return $prefixed_words;
}

Use like this:

$prefixed_words = find_words_prefix("Degree binb 'Information-Systems', 'Computer-Science' , or other KM-relevant field required; graduate degree preferred.", "D");

print_r($prefixed_words);

A similar function can be used for postfixed words

Nikos M.
  • 8,033
  • 4
  • 36
  • 43