Table of Contents



Introduction

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support.

A string literal can be specified in four different ways:

We will discuss each of these methods in the following subsections.

String Concatenation

String concatenation uses the period (.) to append one string of characters to another string. The following examples illustrate this.

Example

String concatenation.

1<?php
2    $count = 10;
3    echo "You have " . $count . " messages.";
4?>
You have 10 messages.

Single-quoted String

If you wish to assign a literal string, preserving the exact contents, you should use single quotation marks (apostrophes).

Example

Declaring strings using single quotes.

1<?php
2    $count = 10;
3    $info = 'There are $count cases.';
4    echo $info
5?>
There are $count cases.

Double-quoted String

If you want to print out value of a variable within a string, you can do so using double-quoted strings.

Example

Declaring strings using double quotes.

1<?php
2    $count = 10;
3    $info = "There are $count cases.";
4    echo $info
5?>
There are 10 cases.

Using double-quoted strings offers a simpler way to print out variables within a string without using concatenation. This is called variable substitution.

Tip

Variable substitution is a faster way to print out variables within a string compared to concatenation.

To display a string that contains quotes, remember to use double quotes to contain single quotes or vice versa. For example, in the following example, the second quotation mark encountered in the term I'd tells the PHP parser that the end of the string has been reached. Therefore, the rest of the string will be rejected as an error.

Example

Including quotes within strings - error.

1<?php
2    $text = 'I'd like to have an ice-cream.'; // wrong syntax
3    echo $text;
4?>
Parse error: syntax error, unexpected identifier "d"...

Instead,since a single quote exists within the string, we should enclose the string in double quotes.

Example

Including quotes within strings - correct way.

1<?php
2    $text = "I'd like to have an ice-cream."; // correct syntax
3    echo $text;
4?>
I'd like to have an ice-cream.

Alternatively, you can add a backslash \ directly before the illegal quotation mark to tell PHP to treat the character literally and not to interpret it. We call the backslash \ followed by the illegal character an escape character.

Example

Including single quotes within strings using escape character.

1<?php
2    $text = 'I\'d like to have an ice-cream.'; // escape
3    echo $text;
4?>
I'd like to have an ice-cream.

We can also use an escape character with double-quoted strings.

Example

Including double quotes within strings using escape character.

1<?php
2    $text = "Singapore is the \"Switzerland\" of the East."; // escape
3    echo $text;
4?>
Singapore is the "Switzerland" of the East.

ADVERTISEMENT



Outputting Long Strings

One simple way to print out a long string is simply to put multiple lines between a pair of quotes (single or double) as the following examples illustrate.

Example

Printing long strings.

1<?php
2    echo "PHP (recursive acronym for PHP: Hypertext Preprocessor) is a
3    widely-used open source general-purpose scripting language that is
4    especially suited for web development and can be embedded into HTML.";
5?>
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

We can also embed single quotes within a pair of double quotes.

Example

Printing long strings with quotes.

1<?php
2    $author = "John Archibald Wheeler";
3    echo " 'At the heart of everything is a question, not an answer.
4    When we peer down into the deepest recesses of matter or
5    at the farthest edges of the universe, we see, finally,
6    our own puzzled face looking back at us.'
7    <BR>
8    - $author.";
9?>
'At the heart of everything is a question, not an answer. When we peer down into the deepest recesses of matter or at the farthest edges of the universe, we see, finally, our own puzzled face looking back at us.'
- John Archibald Wheeler.

Or, if we wish to use double quotes for the string, we can also escape them using the \ character.

Example

Printing long strings with (escaped) double quotes.

1<?php
2    $author = "John Archibald Wheeler";
3    echo " \"At the heart of everything is a question, not an answer.
4    When we peer down into the deepest recesses of matter or
5    at the farthest edges of the universe, we see, finally,
6    our own puzzled face looking back at us.\"
7    <BR>
8    - $author.";
9?>
"At the heart of everything is a question, not an answer. When we peer down into the deepest recesses of matter or at the farthest edges of the universe, we see, finally, our own puzzled face looking back at us."
- John Archibald Wheeler.

Heredoc Syntax

PHP also offers an easy way to print out a multiline sequence of strings using the <<< operator, referred to as heredoc syntax. It preserves the line breaks, quotes and other whitespace (including indentation) in the text.

Example

Printing long strings using heredoc syntax.

 1<?php
 2    $author = "John Archibald Wheeler";
 3    echo <<<_END
 4    "At the heart of everything is a question, not an answer.
 5    When we peer down into the deepest recesses of matter or
 6    at the farthest edges of the universe, we see, finally,
 7    our own puzzled face looking back at us."
 8    <BR>
 9    - $author.
10    _END;
11?>
"At the heart of everything is a question, not an answer. When we peer down into the deepest recesses of matter or at the farthest edges of the universe, we see, finally, our own puzzled face looking back at us."
- John Archibald Wheeler.

Notice that after the heredoc operator <<<, an (user-specified) identifier is provided (END), then a newline. The string itself follows, and then the same identifier again to close the quotation.

The string doesn’t need to be enclosed in quotes, as the next example illustrates.

Example

Printing long strings using heredoc syntax.

1<?php
2    $out = <<<_MSG
3    PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used
4    open source general-purpose scripting language that is especially suited
5    for web development and can be embedded into HTML.
6    _MSG;
7    echo $out;
8?>
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

Nowdoc Syntax

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc.

A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Example

Printing long strings using nowdocs syntax.

 1<?php
 2    $author = "John Archibald Wheeler";
 3    echo <<<'NOD'
 4    "At the heart of everything is a question, not an answer.
 5    When we peer down into the deepest recesses of matter or
 6    at the farthest edges of the universe, we see, finally,
 7    our own puzzled face looking back at us."
 8    <BR>
 9    - $author.
10    NOD;
11?>
"At the heart of everything is a question, not an answer. When we peer down into the deepest recesses of matter or at the farthest edges of the universe, we see, finally, our own puzzled face looking back at us."
- $author.

Note that the variable $author is not parsed within the nowdoc string.

ADVERTISEMENT



PHP String Functions

PHP comes with a number of string functions for manipulating strings. We shall outline a few of the more commonly used ones here. For the complete list, refer to the official documentation .

The PHP strrev() Function.

The PHP strrev() function reverses a string.

Example

The strrev() function.

1<?php
2    echo strrev("abcdef");
3?>
fedcba

The PHP strpos() Function.

The strpos() function searches for a specified text within a string. If a match is found, the function returns the character position of the first match. If no match is found, it will return null.

Example

The strpos() function.

1<?php
2    echo strpos("I love apples!", "apples"); // "apples" starts at pos=7
3?>
7

The PHP str_replace() Function.

The str_replace() function replaces a character (or string) with some other character or string.

Example

The str_replace() function.

1<?php
2    echo str_replace("apples", "oranges", "I love apples!"); // replace "apples" with "oranges"
3?>
I love oranges!

The str_replace() function can be used to remove special characters from a string by specifying an array of characters that are to be replaced. In the following example, the special characters are replaced by -.

Example

The str_replace() function to remove special characters.

1<?php
2    echo str_replace(array("@","#"), "-", "2022@SEP#09") . "<BR>";
3?>
2022-SEP-09

The PHP strlen() Function.

The PHP strlen() function returns the length of a string.

Example

The strlen() function.

1<?php
2    echo strlen("Hello there!"); // including space and !
3?>
12

The PHP str_word_count() Function.

The PHP str_word_count() function counts the number of words in a string.

Example

The str_word_count() function.

1<?php
2    echo str_word_count("I am in Singapore!");
3?>
4

The PHP explode() Function.

The PHP explode() function breaks a string into an array (we shall cover arrays in a later section).

Example

The explode() function - separate by space.

1<?php
2    $str = "Greetings from Singapore!";
3    print_r (explode(" ", $str));
4?>
Array
(
    [0] => Greetings
    [1] => from
    [2] => Singapore!
)

Note that the first argument is the separator (which is a space in this case). We can also separate by a character.

Example

The explode() function - separate by a character.

1<?php
2    $str = "Greetings from Singapore!";
3    print_r (explode("i", $str));
4?>
Array
(
    [0] => Greet
    [1] => ngs from S
    [2] => ngapore!
)

The PHP join() Function.

The PHP join() function returns a string from the elements of an array. The first argument specifies what to put between the array elements. The default is "" (an empty string).

Example

The join() function.

1<?php
2    $arr = array('23', 'Sept', '2022');
3    echo join($arr) . "<br>";
4    echo join(" ", $arr) . "<br>";
5    echo join(".", $arr) . "<br>";
6    echo join("-", $arr) . "<br>";
7?>
23Sept2022
23 Sept 2022
23.Sept.2022
23-Sept-2022