A string variable is used to store and manipulate a piece of text. A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. The simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks (‘), like this:
You can also use double quotation marks (“). However, single and double quotation marks work in different ways. Strings enclosed in single-quotes are treated almost literally, whereas the strings delimited by the double quotes replaces variables with the string representations of their values as well as specially interpreting certain escape sequences.
The escape-sequence replacements are:
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\” is replaced by a single double-quote (“)
\\ is replaced by a single backslash (\)
Here’s an example to clarify the differences between single and double quoted strings:
Following are valid examples of string
$string1 = "This is a simple string"; $string2 = "This is a somewhat longer, singly quoted string"; $string3 = "This string has thirty-nine characters"; $string4 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
<?php $variable = "name"; $literally = 'My $variable will not print!\\n'; print($literally); print "<br />"; $literally = "My $variable will print!\\n"; print($literally); ?>
This will produce the following result −
My $variable will not print!\n My name will print
The PHP strlen() function returns the length of a string. The example below returns the length of the string “Hello world!”:
<?php echo strlen("Hello world!"); // outputs 12 ?>
The PHP str_word_count() function counts the number of words in a string:
<?php echo str_word_count("Hello world!"); // outputs 2 ?>
The PHP strrev() function reverses a string:
<?php echo strrev("Hello world!"); // outputs !dlrow olleH ?>
The PHP str_replace() function replaces some characters with some other characters in a string.
The example below replaces the text “world” with “Rahul”:
<?php echo str_replace("world", "Rahul", "Hello world!"); // outputs Hello Dolly! ?>