note 43838 deleted from function.str-word-count by tomsommer
| From: | tomsommer@php.net | Date: | Tue, 06 Jul 2004 09:09:05 +0000 |
| Subject: | note 43838 deleted from function.str-word-count by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72722@lists.php.net to get a copy of this message | ||
Note Submitter: daz@forumimages.com
----
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.