In the last lesson, PHP Echo, we used strings a bit, but didn’t talk about them in depth. Throughout your PHP career you will be using strings a great deal, so it is important to have a basic understanding of PHP strings.
A string is a sequence of characters
PHPÂ string creation
Before you can use a string you have to create it! A string can be used directly in a function or it can be stored in a variable. Below we create the exact same string twice: first storing it into a variable and in the second case we send the string directly to echo.
Example:
1 2 3 4 | <?php $dcsText = "tutsocean.com!"; //variable that contains a string echo "Best tutorials website for students and developers : <b>".$dcsText.""; ?> |
Common string function:
-
PHPÂ strlen()Â Function
This function is used to find the length of a given string. This function is very common in use as many of the times we need to know the length of the string.
Syntax:
Strlen(string whose length you want to find);
Example:
1234<?php$dcsText = "tutsocean.com!"; //variable that contains a stringecho "Length of given string is : ".strlen($dcsText);?> -
 PHP stripos() Function
This function is used to “Find the position of the first occurrence of some substring inside the string:â€
Syntax
stripos(string,find,start)
Example:
1234<?php$dcsText = "This string contains dcs word three time. Firstone is already written, second and third is here: dcs, dcs"; //variable that contains a stringecho "postion of given word is : ".stripos($dcsText,"dcs");?> -
PHPÂ strcmp()Â Function
This function is used to compare two strings.
Note: The comparison is case sensitive i.e the string “tutsocean†and “TUTSOCEAN†is different.
Syntax:
Strcmp(first string,second string);
Example:
1 2 3 4 5 6 7 8 9 10 11 12 | <?php $dcs_first = "aa"; $dcs_second = "aa"; if(!strcmp($dcs_first, $dcs_second)) { echo "Both strings are having same content"; } else { echo "Strings are not equal"; } ?> |
Note: In the above example, we have used the ! operator which we will learn in detail in the upcoming tuts. If the output of strcmp() function is 0 then that means strings are equal. That’s why we have used ! (NOT) operator.
This is how you can use PHP Strings. Good Luck!