Strings are continues sequence of characters. Strings are used to store values like name of a person, place, thing or any other character based value. A string in PHP is created by enclosing text within single or double quotes. Strings in single quotes are evaluated literally while in double quotes the value of the variables and special characters are printed on the screen. Have a look at the following example to see PHP strings in action.
<?php $color = "red"; $string1 = "The name of the color is $color"; echo $string1.'<br>'; $string2 = 'The name of the color is $color'; echo $string2; ?>
Within the double quotes you can use escape sequences to add tabs, new line and special characters. Following are some of the most commonly used escape sequences in PHP strings.
Have a look at the second example to see how the above escape sequences are used.
<?php $string1 = "The name of \\the color is \"red\" and price is \$ 20"; ?>
PHP strings can be manipulated via Functions. They can be used for plethora of tasks that range from finding the length of the string, concatenating two strings to finding position of a certain character within a string. In our next example, we are going to see some of the most commonly used string functions.
<?php $color = "red"; echo "The length of the string $color is ".strlen($color).'<br>'; echo "The position of first e in $color is ".strpos($color, "e"); ?>
In the above example the strlen function is used to find the length of the string while the strpos function is being used to find the position of specific word within a string. The dot operator “.” is used to concatenate two strings.