Thursday, 1 September 2016

PHP count of occurrences of characters of a string within another string

Let's say I have two strings. $needle = 'AGUXYZ'; $haystack = 'Agriculture ID XYZ-A'; I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive). function count_occurences($char_string, $haystack, $case_sensitive = true){ if($case_sensitive === false){ $char_string = strtolower($char_string); $haystack = strtolower($haystack); ...

How can I count white spaces using substr_count() in PHP

One way could be to remove all other characters and count what's left. You could do this with something like the following: <?php $text = 'This is a test';  echo substr_count($text, ' '); // 3 // $count_var = preg_replace('[^\s]', '', $string); $count = strlen($count_var);//Replace any non-whitespace with nothing, count the result: echo strlen(preg_replace('/\S/', '', $text));//This works for any whitespace, including tabs the like.substr_count should work fine though for regular spaces:echo substr_count($text, ' '); $test = "sadlk...

PHP : substr_count() function

substr_count() function Description The substr_count() function is used to count the number of times a substring occurs in a string. Note that substring is case sensitive. Version (PHP 4 and above) Syntax substr_count(string1, string2, nstart, nlength) Parameters NameDescriptionRequired /OptionalType string1The string to search in.RequiredString string2The substring to search for.RequiredString nstartThe position where string to start searching.OptionalInteger nlengthThe length of the string to be searched for.OptionalInteger Return...