This entry is part 5 of 6 in the series PHP String Functions

In most cases we have to find the information related to string like string length, get words counts, etc.

PHP has a bunch of functions which used to get the infomation from the string. Below are those functions:

  • strlen()
  • count_chars()
  • str_word_count()
  • substr_count()
  • chr()
  • ord()

Let’s get into each one:

strlen()

This function is used to find the length of the string. I think this is the most used function from above functions.

This function string as a argument.

Usage:

echo strlen('This is the string.');
# Output : 19

count_chars()

This function will return the character used in the string. i.e: 2 D, 3r, so on..
This function takes two arguments, first one is string which needs be analyzed and second is the return mode.
Based on second parameter this function will return a proper value.

Here are the diff output format of the function based on second parameter.

0 – an array with the byte-value as key and the frequency of every byte as value.
1 – same as 0 but only byte-values with a frequency greater than zero are listed.
2 – same as 0 but only byte-values with a frequency equal to zero are listed.
3 – a string containing all unique characters is returned.
4 – a string containing all not used characters is returned.

Usage:

$data = 'This is the string.';
$data = count_chars($data, 1);

str_word_count()

This function will return information about words used in a string.

This takes three parameters.

First is the string which needs to analyze, second is the format which defines the return type. Third is the character list which defines the charachters which should be considered as words.

Here are the diff output format of the function based on second parameter.

0 – Return the number word found.
1 – Return an array with words.
2 – Return an array where key is the position of the worb.

Usage:

$data = 'This is the string.';
$return = str_word_count($data,0);
$return = str_word_count($data,1);
$return = str_word_count($data,2,'qwetgf');

substr_count()

This function count the occurences of the substring from the main string.

This takes four arguments.

First argument is the main string. Second is the substring whose count you want.

Rest of the parameters are optional.

Third parameter defines the offset from where it should start searching for the substring. Fourth argement defines the maximum length after specified offset in third argument.

Note: This function doesn’t count overlapped substrings.

Usage:

$data = 'This is the string.';
echo substr_count($data, 'the'); //1

chr()

This function return a specific character from the ascii value.

Usage:

echo chr(27);

ord()

This function will return a ASCII value of the chanracter.

Usage:

echo ord('f');

Series NavigationPHP Encode-Decode FunctionsPHP String Formatting Functions