Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count no.of characters in a string without spaces and special characters?

Tags:

string

php

We have strlen and mb_strlen of the count the string but that give the all the characters in the string . I want to count only character [a-z][A-Z] in the given string is there any per defined function .Or we need to develop our own logic.

like image 207
vijaykumar Avatar asked Oct 26 '13 08:10

vijaykumar


People also ask

How do you count characters in a string without spaces?

And to count character without space, we have to check how many spaces are present inside the string. Then subtract total character (countWithSpace holds the value of total character) with spaces, that will be the number of character without space. Therefore, initialize it to countWithoutSpace variable.

Do you count characters with or without spaces?

Yes, the character count includes all spaces, punctuation and letters. Anything that moves your cursor counts as a character.

How do I count characters in Excel without spaces?

To get the a total count of all the characters in several cells is to use the SUM functions along with LEN. In this example, the LEN function counts the characters in each cell and the SUM function adds the counts: =SUM((LEN( cell1 ),LEN( cell2 ),(LEN( cell3 )) )).


2 Answers

Tested

The following regex replaces all numbers, symbols & spaces. Shortly saying.. it will allow only alphabets A-Z and a-z, others won't be taken into account.

<?php
$str='Hello World345345 *90234 $$5assd54';
$str = preg_replace("/[^A-Za-z]/","",$str);
echo $str;//HelloWorldassd
echo strlen($str);//14
like image 151
Shankar Narayana Damodaran Avatar answered Oct 21 '22 13:10

Shankar Narayana Damodaran


I think you'll need to use your own logic. If you're only interested in counting a-z and A-Z then this should work:

<?php
$string= 'This is my sample string.';

echo "Everything: ".strlen($string);
echo '<br />';
echo "Only alphabetical: ".strlen(preg_replace('/[^a-zA-Z]/', '', $string));
?>

Basically that's just removing everything that isn't in our allowed characters list then counting the characters in the result.

like image 27
Clart Tent Avatar answered Oct 21 '22 13:10

Clart Tent