A string can be defined as a combination of characters. We'll look into some commonly used string functions in PHP.
str_word_count()
This function counts the words in a string.
Let's look at the code below:
<?phpecho str_word_count("Learn from Educative!"); // outputs 3?>
There are 3 words in this string "Learn from Educative!"
.
strlen()
This function returns the length of a string.
Let's look at the code below:
<?phpecho strlen("Learn from Educative!"); // outputs 21?>
The length of the string "Learn from Educative!"
is returned. In this case, the length returned is 21
characters.
strpos()
This function searches the given string from the larger(main) string. Character position of the first match is returned, otherwise, false is returned.
Let's look at the code below:
<?phpecho strpos("Learn from Educative!", "Educative"); // outputs 11?>
The first character position in a string is 0. Keeping this in mind, "Educative"
starts from the
strrev()
This function will reverse a string.
Let's look at the code below:
<?phpecho strrev("Learn from Educative!"); // outputs !evitacudE morf nraeL?>
It reverses the given string "Learn from Educative!"
.
str_replace()
This function will replace some characters with some other characters in a string.
Let's look at the code below:
<?phpecho str_replace("from", "through", "Learn from Educative!"); // outputs Hello Dolly!?>
It replaces the word "from"
with "through"
in the string.