In this section, we will discuss a few basic string functions which are most commonly used in PHP scripts.
1. Getting length of a String: PHP has a predefined function to get the length of a string. Strlen() displays the length of any string. It is more commonly used in validating input fields where the user is limited to enter a fixed length of characters.
Output
20
2. Counting of the number of words in a String: Another function that enables the display of the number of words in any specific string is str_word_count(). This function is also useful in the validation of input fields.
Output
3
3. Reversing a String: Strrev() is used for reversing a string. You can use this function to get the reverse version of any string.
Output
syawduolC ot emocleW
4. Finding Text Within a String: Strpos() enables searching particular text within a string. It works simply by matching the specific text in a string. If found, then it returns the specific position. If not found at all, then it will return “False”. Strops() is most commonly used in validating input fields like email.
Output
11
5. Replacing text within a string: Str_replace() is a built-in function, basically used for replacing specific text within a string.
Output
Welcome to the programming world
6. Converting lowercase into Title Case: Ucwords() is used to convert first alphabet of every word into uppercase.
Output
Welcome To The Php World
7. Converting a whole string into UPPERCASE: Strtoupper() is used to convert a whole string into uppercase.
Output
WELCOME TO CLOUDWAYS
8. Converting whole String to lowercase: Strtolower() is used to convert a string into lowercase.
?>
Output
welcome to cloudways
9. Repeating a String: PHP provides a built-in function for repeating a string a specific number of times.
?>
Output
=============
10. Comparing Strings: You can compare two strings by using strcmp(). It returns output either greater than zero, less than zero or equal to zero. If string 1 is greater than string 2 then it returns greater than zero. If string 1 is less than string 2 then it returns less than zero. It returns zero, if the strings are equal.
Output
1
0
-1
-1
-4
11. Displaying part of String: Through substr() function you can display or extract a string from a particular position.
Output
e to Cloudways
Welcome to
12. Removing white spaces from a String: Trim() is dedicated to remove white spaces and predefined characters from a both the sides of a string.
<?php$str = “Wordpess Hosting”;echo $str . “<br>”;echo trim(“$str”,”Wording”);?>
Output
Wordpess Hosting
pess Host