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

    $characters = str_split($char_string);
    $character_count = 0;
    foreach($characters as $character){
        $character_count = $character_count + substr_count($haystack, $character);
    }
    return $character_count;
}
To use;
$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
print count_occurences($needle, $haystack);
You can set the third parameter to false to ignore case.

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 asd sad sda";
$whitespaces = substr_count($test," ");


?>

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 /
Optional
Type
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 value

Returns a number.
Value Type : Integer.

Example :

  1. <?php  
  2. $string1="Welcome to w3resource.com";  
  3. echo substr_count($string1,'co');   
  4. echo substr_count($string1,'co',4);   
  5. echo substr_count($string1,'co',4,4);   
  6. ?>  

Output

2
1
0