How to find number of characters or length of a string in PHP

There are lot of useful string functions available in PHP. You can use them to meet many functionalities while programming in PHP in your project. One such function is strlen() in PHP which gives the number of characters in a string or length of a string.

In this topic, I will write a simple PHP program to print number of characters in a string. See the below code to get the string length or number of characters:

I will write a simple program to print number of characters in a string. Let me show you the code below for this purpose:

I am using a PHP variable $str to hold the input string, number of characters of which I want to count. String function strlen($str) is counting the number of characters. Then using echo I am displaying the count. I named this file as index.php and saved it in a folder "char_count" under htdocs.

Let me now test it.

character count in phpTest the Application

Make sure your in your XAMPP control panel Apache is running. Open the browser and run localhost/char_count. You will see the page opened with count displayed in blue color.

Character Count in PHP

You can see it is counting the spaces also. If you want to count number of characters without spaces, you can change a little bit as below:

Before using strlen() function, I used str_replace() function to remove spaces. Now see the modified code for index.php. I want to display counts including spaces as well as count without spaces.

You can see I have added str_replace() PHP function and then counting for without spaces. Then printing it separately in line 15.

If you test it now, it will display both the counts, with spaces and without spaces. See below output:

Character Count in PHP

number of characters in string in phpImportant Note

  1. While working in the project you might come across requirements to count the number of characters in a string with/without spaces or to remove spaces in a string. So, you can use these functions wherever applicable. One point you must note that a string can have tab spaces also. In that case this example will not work, because I am removing spaces only. To remove tabs, you can use preg_replace() function.
  2. If the input string is empty, strlen() will return 0, which means number of characters in the string is 0.

php string functionsDownload Source Code

I have put all codes in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can directly use the code or you can modify them as per your requirements.

php length of a stringConclusion

This is an example of using string function in PHP. There are many useful string functions available in PHP, you can use them during PHP programming. Purpose of this example was to show how you can use PHP string function while you are practicing PHP program.