PHP String

In this lesson, you will learn about Strings in PHP, their usage, and examples to better understand the topic.


PHP Strings

PHP strings are a group of characters used to store and alter the content. PHP does not provide native Unicode support because it only supports a 256-character set. In PHP, a literal string specifies in four different ways, and we will study 2 in later tutorials.

  • Single-quote strings
  • Double quoted strings

Single-quote strings

We can generate a string in PHP by surrounding the content in a single quote. In PHP, it is the simplest way to specify a string. Escape a single literal quotation with a backslash \, and use double backslashes to specify a literal backslash \\. The output of all other backslash characters, such as r and n, will be without additional context.

Example

<!DOCTYPE html>
<html>
<body>
<?php
$stringVariable = 'Let’s see the result';
$stringVariable1 = 'This is my
Single quoted string
that is also multiline';
$stringVariable2 = 'Let’s use the "quote" directly here';
$stringVariable3 = 'Wao escape sequences \n in single quoted string';

echo "$stringVariable <br/> $stringVariable1 <br/> $stringVariable2 <br/> $stringVariable3";
?>
</body>
</html>

Output

Let’s see the result
This is my Single quoted string that is also multiline
Let's use the "quote" directly here
Wao escape sequences \n in a single-quoted string

Double quoted strings

We can define a string in PHP by enclosing the text in double-quotes. You will learn about variables and escape sequences by using double-quote PHP strings. Using a double quote inside another double quote is currently not permitted.

A double-quoted PHP string allows us to store multiple lines of text, special characters, and escape sequences.

Note
We can’t use Double quotes currently inside other double quotes. If we don’t use the escape character in the example below, the program will throw a parses error.

“Parse error: syntax error, unexpected ‘quote’ (T_STRING) in line”

Example

<!DOCTYPE html>
<html>
  <body> <?php
$stringVariable1="This is my
Single quoted string
that is also multiline";
$stringVariable2="Let’s use the \"quote\" directly here";
$stringVariable3="Wao escape sequences \n in single quoted string";
$stringVariable3="Let’s see the result";
echo "$stringVariable1 
        <br/> $stringVariable2 
        <br/> $stringVariable3";

?> </body>
</html>

Output

This is my Single quoted string that is also multiline
Let's use the "quote" directly here
Let's see the result

This concludes the PHP String lesson. In the next lesson, you will learn about PHP String Functions.