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.
$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.
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:”
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.
Strcmp(first string,second string);
$dcs_first = "aa";
$dcs_second = "aa";
echo "Both strings are having same content";
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.