note 43838 added to function.str-word-count
| From: | daz at forumimages dot com | Date: | Tue, 06 Jul 2004 00:42:28 +0000 |
| Subject: | note 43838 added to function.str-word-count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-72637@lists.php.net to get a copy of this message | ||
Probably not the most efficient (or right) solution to this, but 'tis late and I is a tired
newbie ;)
*SHOULD* work as the real function, but not done too much testing...
<?php
if ( !function_exists('str_word_count') )
{
function str_word_count($string, $format = null)
{
// Daz [at] ForumImages [dot] com
// requires PHP 4 >= 4.0.1 for 'trigger_error'
if ( $format != 1 && $format != 2 && $format !== null )
{
trigger_error("str_word_count() The specified format parameter, '$format' is
invalid", E_USER_WARNING);
return false;
}
$word_dashes = '___dDaShB___';
$word_quotes = '___dQuOtEB___';
$word_string = preg_replace(array('#\\b-\\b#', "#\\b'\\b#",
'#[\\W\\d]#'), array($word_dashes, $word_quotes, ' '), $string);
$word_array = preg_split("/[^\\w]+/", $word_string, -1, PREG_SPLIT_NO_EMPTY);
if ( $format >= 1 )
{
$lastposition = 0;
$word_assoc_array = array();
for ( $i = 0; $i < count($word_array); $i++ )
{
$word_array[$i] = str_replace(array($word_dashes, $word_quotes), array('-',
"'"), $word_array[$i]);
$word = $word_array[$i];
$word_assoc_array[$lastposition = strpos($string, $word, $lastposition)] = $word;
$string = substr_replace($string, str_repeat(' ', strlen($word)), $lastposition,
strlen($word));
}
$return = ( $format == 2 ) ? $word_assoc_array : $word_array;
}
else
{
$return = count($word_array);
}
return $return;
}
}
?>
The basic framework is from the unfinished PHP_Compat replacement - so partial credit goes to Aidan
Lister.
----
Manual Page -- http://www.php.net/manual/en/function.str-word-count.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+43838
Delete -- http://master.php.net/manage/user-notes.php?action=delete+43838&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+43838&report=yes
Search -- http://master.php.net/manage/user-notes.php