Returning number of times a string present inside another string.

Within a string we can count number of occurrence of another string by using substr_count function. This function takes the main string and the search string as inputs and returns number of time search string is found inside the main string.

Here is the syntax

substr_count(“main string”,"search_string");
Let us try with an example

$my_string="PHP is a server side script and learn PHP at";
echo substr_count($my_string,"PHP");
The above code will print 2
Related Tutorial
Counting words
Counting Chars

Another useful requirement of this functions is calculating how many email address entered by the user in an input field. If you are using one form and sending the form by email where to address is entered by the user. Spammers can use this by placing more than one email address inside the input field. We can count the number of @ used within the input field and display error message. Here is the code

if(substr_count($y_email,"@") > 1  ){
$msg .="Use only one email address<BR>";

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
Your Rating


PHP String Functions


Thanks for sharing this example. Very useful.


Very useful thanks!

Post Comment This is for short comments only. Use the forum for more discussions.

Subscribe to our mailing list

* indicates required
Subscribe to plus2net
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2018 All rights reserved worldwide Privacy Policy Disclaimer