homlyn
homlyn

Reputation: 253

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 number including spaces.

Upvotes: 0

Views: 681

Answers (6)

Tim Pietzcker
Tim Pietzcker

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

0x1F602
0x1F602

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

Andrew Jackman
Andrew Jackman

Reputation: 13966

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

This is the total length - the number of spaces.

Upvotes: 2

Phoenix
Phoenix

Reputation: 4536

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

Upvotes: 0

Jon
Jon

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

Nick Larsen
Nick Larsen

Reputation: 18877

Rewrite strlen that doesn't count spaces.

Upvotes: 0

Related Questions