PHP string tutorial

Home - Tutorials - Basics

A detailed description how to use PHP strings and string manipulation functions.

Tutorial info:

Name:PHP string tutorial
Total steps:3

Bookmark PHP string tutorial

Bookmark and Share

Step 1 - PHP string basic

PHP string tutorial

String is a type in PHP and it is a series of characters. There are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode.
However I have a good news as well as there is no limitation in string length in PHP (Of course available memory and PHP ini settings can reduce it).

You can set a string in three different ways. It's up to you what method do you use, all have pros.

  1. The first and most known way is to specify a string in single quotes. Similar to other programing languages you need to use backslash '\' if you want to display a single quote in your text.
    1. <?php
    2. $str_1 = 'Demo text';
    3. $str_2 = 'Demo text with single quote(\')';
    4. echo $str_1;
    5. echo $str_2;
    6. ?>
  2.  The second option to use double quotes. Between double quotes you can use more escape character in your string. Besides this if you put a variable in the string then PHP will interpret it and display the content of the variable.
    1. <?php
    2. $str_1 = "Demo text";
    3. $str_2 = "Demo text with double quote(\")\r\n";
    4. $demo = "Internal";
    5. $str_3 = "This is a $demo string";
    6. echo $str_1;
    7. echo $str_2;
    8. echo $str_3;
    9. ?>

    Here the most important part is the string defined as $str_3 and its output in line 8 will result this:

    This is a Internal string

  3. And last you can use heredoc as well. In this case you define your text between heredoc identifiers. In this case it is DEMO. You need to start it with the operator <<< and then the identifier. If you are ready you need to close the heredoc part by adding the identifier again at the beginning of a new line like this:
    1. <?php
    2. $str_1 = <<<DEMO
    3. This is a heredoc message
    5. Text.
    6. DEMO;
    8. echo $str_1;
    9. ?>

    As you can see the output is in the same formatting - text indent, new lines - as it was defined. You can use variables in case of heredoc as well as in case of double quoted strings.

The 2. case is the most interesting string definition version so let's see a bit more how to insert a variable inside a string. (You can use variables in case 3. as well but heredoc is not so common.)

Next Step of PHP string tutorial

Tags: php string, php string function, string, php

Follow phpf1 on Twitter

F1 Site Family
Database F1
Java F1
JavaScript F1

Total time: 0.0338