Kira perkataan di dalam string - PHP

22:44 / Comments (0) / by SeLaMbeR

Counts the number of words inside string. If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format. The possible value for the format and the resultant outputs are listed below.

For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.



Description:

The first argument “string” is Required. It specifies the string to check.
The second argument “format” is Optional. It Specifies the return value of the str_word_count() function.
The following Possible values are:
* 0 – Default. Returns the number of words found.
* 1 – Returns an array with the words from the string.
* 2 – Returns an array where the key is the position of the word in the string, and value is the actual word.
The third argument “char” is Optional. It specifies special characters to be considered as words.

<?php

$str = "All that glitters is not gold";
echo str_word_count($str)."<br>";
print_r(str_word_count($str,1));
print_r(str_word_count($str, 2));
$str1="Tom & Jerry";
print_r(str_word_count($str1,1));
print_r(str_word_count($str1,1,"&"));

?>


Output:
6
Array (
[0] => All
[1] => that
[2] => glitters
[3] => is
[4] => not
[5] => gold
)
Array (
[0] => All
[4] => that
[9] => glitters
[18] => is
[21] => not
[25] => gold
)
Output:
str_word_count() without and with the char parameter:

Array (
[0] => Tom
[1] => Jerry
)
Array (
[0] => Tom
[1] => &
[2] => Jerry
)

Some advance useful function

<?php

/**
 * Returns the number of words in a string.
 * As far as I have tested, it is very accurate.
 * The string can have HTML in it,
 * but you should do something like this first:
 *
 *    $search = array(
 *      '@<script[^>]*?>.*?</script>@si',
 *      '@<style[^>]*?>.*?</style>@siU',
 *      '@<![sS]*?--[ tnr]*>@'
 *    );
 *    $html = preg_replace($search, '', $html);
 *
 */

function word_count($html) {

  # strip all html tags
  $wc = strip_tags($html);

  # remove 'words' that don't consist of alphanumerical characters or punctuation
  $pattern = "#[^(w|d|'|"|.|!|?|;|,|\|/|-|:|&|@)]+#";
  $wc = trim(preg_replace($pattern, " ", $wc));

  # remove one-letter 'words' that consist only of punctuation
  $wc = trim(preg_replace("#s*[('|"|.|!|?|;|,|\|/|-|:|&|@)]s*#", " ", $wc));

  # remove superfluous whitespace
  $wc = preg_replace("/ss+/", " ", $wc);

  # split string into an array of words
  $wc = explode(" ", $wc);

  # remove empty elements
  $wc = array_filter($wc);

  # return the number of words
  return count($wc);

}

?>



0 comments:

 
Share