S
S
Stepan2012-06-08 14:49:57
PHP
Stepan, 2012-06-08 14:49:57

php. How to get an array of the words of a string?

Hello. Can you tell me how to get an array of words and the number of occurrences from a string?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
ssbxlan, 2012-06-08
@ssbxlan

preg_split by punctuation
array_count_values

S
Sergey Beresnev, 2012-06-08
@sectus

To put it simply, you can do something like this.

$array = array_filter(explode(' ', $string)); 
$count_array = array_count_values($array); 
var_dump($count_array);

N
Nazar Mokrinsky, 2012-06-30
@nazarpc

Why make it so difficult? There are also standard functions for most of the trivial tasks.
str_word_count — Returns information about the words in a string

D
dsd_corp, 2012-06-08
@dsd_corp

  $str=file_get_contents('./words.txt');
  $aw=preg_split('/[\W]+/', $str);
  $wc=array_count_values($aw);
  file_put_contents('./words_out.txt', var_export(array($aw, $wc), true));

Words.txt content
php. Как получить массив слов строки?
PHP*
Здравствуйте. Не подскажете как из строки получить массив слов и количество вхождений?
php


The content of words_out.txt after processing
array (
  0 => 
  array (
    0 => 'php',
    1 => 'Как',
    2 => 'получить',
    3 => 'массив',
    4 => 'слов',
    5 => 'строки',
    6 => 'PHP',
    7 => 'Здравствуйте',
    8 => 'Не',
    9 => 'подскажете',
    10 => 'как',
    11 => 'из',
    12 => 'строки',
    13 => 'получить',
    14 => 'массив',
    15 => 'слов',
    16 => 'и',
    17 => 'количество',
    18 => 'вхождений',
    19 => 'php',
  ),
  1 => 
  array (
    'php' => 2,
    'Как' => 1,
    'получить' => 2,
    'массив' => 2,
    'слов' => 2,
    'строки' => 2,
    'PHP' => 1,
    'Здравствуйте' => 1,
    'Не' => 1,
    'подскажете' => 1,
    'как' => 1,
    'из' => 1,
    'и' => 1,
    'количество' => 1,
    'вхождений' => 1,
  ),
)

S
softm, 2012-06-09
@softm

All examples are good, but don't forget about word length and stop list
Probably also need
foreach ( $wc as $k=>$x) if (strlen($x)==1 || in_array($x,$stop_list) )unset $wc[$k]
before counting.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question