Count occurrences of a character in a String in PHP

By: Kani  

Here is another simple example for - for loops. Thsi PHP code shows how to search for a particular character in a String and count the number of occurrences of that character in that string.

<?php

$text="Welcome to PHP";
$searchchar="e";
$count="0"; //zero

for($i="0"; $i<strlen($text); $i=$i+1){
   
    if(substr($text,$i,1)==$searchchar){
   
       $count=$count+1;
    }

}

echo $count

?>

this will count how many times the character "e" occurs in that text (Welcome to PHP).




Archived Comments


Most Viewed Articles (in PHP )

Polymorphism in PHP

PHP file upload with IIS on windows XP/2000 etc

PHP file upload (Large Files)

Installing PHP with nginx-server under windows

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to force strict boolean values in PHP

Function to sort array by elements and count of element in PHP

Function to convert strings to strict booleans in PHP

Latest Articles (in PHP)

Comment on this tutorial