$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
substr_count(string $haystack,string $needle,int $offset, int $length);
Parameter | DESCRIPTION |
---|---|
$haystack | Required : Input string |
$needle | Required : substring to be searched within Input string |
$offset | Optional : Where to start counting. If negative (in PHP 7 only ) then from end of the input string |
$length | Optional : The maximum length after the $offset to search for the substring. If negative ( in PHP 7 only ) then count from end of the haystack ( input string ) only. Sum of offset and $length should not be more than the lenght of $haystack ( Warning as output ) |
$string="Welcome to plus2net.com, you can add your comment";
echo strlen($string); // Output is 49 ( length of the string )
echo substr_count($string,'com'); // Output is 3
echo substr_count($string,'com',3); // Output is 3
echo substr_count($string,'com',4); // Output is 2
echo substr_count($string,'com',20); // Output is 2
echo substr_count($string,'com',21); // Output is 1
echo substr_count($string,'com',3,3); // Output is is 1
echo substr_count($string,'com',4,3); // Output is is 0
echo substr_count($string,'com',0,10); // Output is 1
echo substr_count($string,'com',4,18); // Output is 0
echo substr_count($string,'com',4,19); // Output is 1
echo substr_count($string,'com',4,18); // Output is 0
echo substr_count($string,'com',20); // Output is 2
echo substr_count($string,'com',20,29); // Output is 2
echo substr_count($string,'com',20,30); // Warning as 20 + 30 is greater than 49
$string="Welcome to plus2net.com, you can add your comment";
//echo strlen($string); // Output is 49 ( length of the string )
///////// PHP 7 //////////////
echo substr_count($string,'com',-49); // Output is 3
echo substr_count($string,'com',-49,-4); // Output is 3
echo substr_count($string,'com',-49,-5); // Output is 2
echo substr_count($string,'com',-47,-4); // Output is 3
echo substr_count($string,'com',-49,-7); // Output is 2
echo substr_count($string,'com',-49,-26);// Output is 2
echo substr_count($string,'com',-49,-27);// Output is 1
echo substr_count($string,'com',-29,-26);// Output is 1
echo substr_count($string,'com',-28,-26);// Output is 0
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>";
}
Paul, copySnips.com | 02-09-2009 |
Thanks for sharing this example. Very useful. |
John | 13-10-2014 |
Very useful thanks! |