SQL PHP HTML ASP JavaScript articles and free scripts to download
 

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 www.plus2net.com";
echo substr_count($my_string,"PHP");

The above code will print 2

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>";
}



You can see this script in use in tell a friend script.



Paul, copySnips.com02-09-2009
Thanks for sharing this example. Very useful.
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked


Join Our Email List
Email:  
For Email Newsletters you can trust
String Functions
PHP Sections