vijaykumar
vijaykumar

Reputation: 4806

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

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.

Upvotes: 8

Views: 15887

Answers (5)

Rahul Prasad
Rahul Prasad

Reputation: 8222

Or you can write your custom code like this

<?php
$x = "rahul";
$len = strlen($x);
$myLen = 0;
for($i =0; $i < $len ; $i++) {
  if(!( $x[$i]==" " || $x[$i]=="/" || $x[$i]=="&" )) { // Add more conditions here
    $myLen++;
  }
}

Upvotes: 0

user3473916
user3473916

Reputation: 17

$word = explode( ' ',$sentence ); 

$words = count( $word );

Upvotes: 0

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

Upvotes: 9

Aif
Aif

Reputation: 11220

I suggest using regular expressions, and the fact that preg_match_all returns the number of matches. Why RE? Because you may often have to add new chars to translate in order to count the actual size.

<?php

$str = ' this is my String with spécial chars';
echo strlen($str) . "\n";

echo preg_match_all ('/[A-Za-z]/', $str, $out) . "\n" ;

Produces 38 and 29.

Upvotes: 0

Clart Tent
Clart Tent

Reputation: 1309

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.

Upvotes: 7

Related Questions