Reputation: 253
How do you calculate number of letters in a sentence like below using PHP?
hello how are you
strlen
gives total number including spaces.
Upvotes: 0
Views: 681
Reputation: 336128
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.
Upvotes: 0
Reputation: 865
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);
Upvotes: 0
Reputation: 13966
$letter_count = strlen( $string ) - substr_count($string , ' ');
This is the total length - the number of spaces.
Upvotes: 2
Reputation: 4536
$string = 'hello how are you';
$spaceless = str_replace(' ','',$string);
$totalcharswithspaces = strlen($string);
$totalchars = strlen($spaceless);
Upvotes: 0
Reputation: 437356
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.
Upvotes: 1