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
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP convert string to lower case
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8