In PHP, a string is a sequence of characters, like “Hello World”. Strings can be surrounded by either single or double quotes, and you can use one type of quotes to define a string that contains the other type of quotes. For example:
$string1 = 'Hello World';
$string2 = "Hello World";
$string3 = 'I said "Hello World"';
$string4 = "I said 'Hello World'";
There are several ways to manipulate strings in PHP:
- Concatenation – Use the “.” operator to concatenate two strings, like this:
$string1 = 'Hello';
$string2 = 'World';
$string3 = $string1 . ' ' . $string2; // $string3 is now "Hello World"
- Escaping characters – Use a backslash () to escape characters that have a special meaning in PHP. For example:
$string1 = 'I\'m a string'; // $string1 is now "I'm a string"
$string2 = "This is a new line\n"; // $string2 is now "This is a new line" followed by a new line
- String functions – PHP has many built-in functions for manipulating strings, such as strlen(), strtoupper(), and substr(). For example:
$string = 'Hello World';
echo strlen($string); // Outputs 11
echo strtoupper($string); // Outputs HELLO WORLD
echo substr($string, 6); // Outputs World