Programming Tutorials

Count occurrences of a character in a String in PHP

By: Kani in PHP Tutorials on 2012-04-05  

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).






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Send push notifications using Expo tokens in PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Decrypting files using GnuPG (GPG) via PHP

Count occurrences of a character in a String in PHP

Password must include both numeric and alphabetic characters - Magento

Error: Length parameter must be greater than 0

Reading word by word from a file in PHP

Parent: child process exited with status 3221225477 -- Restarting

Convert a hex string into a 32-bit IEEE 754 float number in PHP

Using Text file as database in PHP

Latest Articles (in PHP)