开发者

counting letters in a sentence

How do you calculate number of letters in a sentence like below using PHP?

hello how are you

strlen gives total numbe开发者_开发问答r including spaces.


$letter_count = strlen( $string ) - substr_count($string , ' ');

This is the total length - the number of spaces.


You can strip out the spaces with str_replace:

$stripped = str_replace(' ', '', 'hello how are you');

Then it's easy to count the remaining characters.


Rewrite strlen that doesn't count spaces.


$string = 'hello how are you';
$spaceless = str_replace(' ','',$string);
$totalcharswithspaces = strlen($string);
$totalchars = strlen($spaceless);


if you want frequency information too...


$strip_chars = array(" "); //this is expandable now
$array_of_used_characters = count_chars(str_replace($strip_chars, '', $sentence), 1);
var_dump($array_of_used_characters);


You could first remove all non-letters:

$result = preg_replace('/\P{L}+/u', '', $subject);

and then do mb_strlen($result).

\p{L} is the regular expression for "any Unicode letter".

\P{L} is its inverse - anything but a letter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜