- PHP string
- PHP string literal
- PHP string heredoc
- PHP string nowdoc
- PHP string interpolation
- PHP string concatenation
- PHP escape characters
- PHP string functions
- PHP array of chars
- PHP string formatting
- PHP String
- Introduction to PHP strings
- Single-quoted strings vs. double-quoted strings
- Accessing characters in a string
- Getting the length of a string
- Summary
PHP string
In this part of the PHP programming tutorial, we work with string data in more detail.
$ php -v php -v PHP 8.1.2 (cli) (built: Aug 8 2022 07:28:23) (NTS) .
A string is series of characters, where a character is the same as a byte.
PHP only supports a 256-character set; it does not offer native Unicode support.
PHP string literal
A string literal is the notation for representing a string value within the text of a computer program. In PHP, strings can be created with single quotes, double quotes or using the heredoc or the nowdoc syntax.
In this code example, we create two strings and assign them to $a and $b variables. We print them with the echo keyword. The first string is created with the double quote delimiters, the second one with single quotes.
PHP string heredoc
The closing identifier must not be indented. It can only contain alphanumeric characters and underscores, and must start with a non-digit character or underscore.
The example prints an example of a direct speech.
$ php heredoc.php "That is just as I intended." Vautrin said. "You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you."
PHP string nowdoc
A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. A nowdoc is identified with the same
The example prints three sentences using the nowdoc syntax.
$ php nowdoc.php Fear is among the greatest obstacles which prevent us from enjoying life to its fullest extent. Since of the most commonly held fears among people are the fear of heights and the fear of falling from heights. Rock climbing is a fantastic way to conquer these fears.
PHP string interpolation
Variables are interpolated in strings enclosed by double quotes.
The $quantity variable is replaced with its value in the string output.
$ php interpolation.php There are 5 roses in the vase
Curly braces can be used when the variable name is next to another character.
Without the curly braces, the PHP interpreter would look for the $item_names variable, which does not exist.
$ php curly_braces.php There are 5 roses in the vase
PHP string concatenation
PHP uses the dot . operator to concatenate strings.
php > echo "PHP " . "language\n"; PHP language
The example concatenates two strings.
php > $a = "Java "; php > $a .= "language\n"; php > echo $a; Java language
PHP also supports the .= compound operator.
PHP escape characters
An escape character is a single character designated to invoke an alternative interpretation on immediately subsequent characters in a character sequence.
The carriage return \r is a control character for end of line return to the beginning of line.
The new line is a control characters which begins a new line of text.
$ php strophe.php Incompatible, it don't matter though 'cos someone's bound to hear my cry Speak out if you do You're not easy to find
php> echo "Towering\tinferno\n"; Towering inferno
The horizontal tab puts a space between text.
Single and double quotes can be nested. Or in case we use only single quotes, we can use the backslash to escape the default meaning of a single quote.
In this example, we have a multiline text, which includes direct speech. The double quotes are escaped with the backslash character.
php> $var = 233; php> echo "$var"; 233 php> echo "\$var is $var"; $var is 233
The dollar sign $ has also a special meaning in PHP; it denotes a variable. If a variable is used inside a string, it is interpolated, i.e. the value of the variable is used. To echo a variable name, we escape the $ character \$ .
PHP string functions
PHP has a large number of useful useful built-in functions that can be used for working with strings.
echo strlen("Eagle"); # prints 5 echo strtoupper("Eagle"); # prints EAGLE echo strtolower("Eagle"); # prints eagle
Here we use three functions. The strlen function returns a number of characters in the string. The strtoupper converts characters to uppercase letters, and the strtolower converts characters to lowercase letters.
echo "There are $length characters.\n"; echo "There are $alphas alphabetic characters.\n"; echo "There are $digits digits.\n"; echo "There are $spaces spaces.\n";
In our example, we have a string sentence. We calculate the absolute number of characters, number of alphabetic characters, digits and spaces in the sentence. To do this, we use the following functions: strlen , ctype_alpha , ctype_digit , and ctype_space .
$ php letters.php There are 19 characters. There are 14 alphabetic characters. There are 2 digits. There are 3 spaces.
Next, we cover the substr function.
echo substr("PHP language", 0, 3); # prints PHP echo substr("PHP language", -8); # prints language
The function returns a part of a string. The first parameter is the specified string. The second parameter is the start of the substring. The third parameter is optional. It is the length of the returned substring. The default is to the return until the end of the string.
The str_repeat function repeats a string a specified number of times.
We use the str_repeat function to create two lines of the # character.
$ php repeat.php ################## Project Neurea Priority high Security maximum ##################
In the next example, we randomly modify a string.
The str_shuffle randomly shuffles a string.
$ php shuffling.php ZtCeoed eodtCZe toZeeCd oCdeteZ edtCZoe tdeCeoZ oeZdteC
This is a sample output of the shuffling.php script.
The explode function is used to split a string into parts. It returns an array of split string parts. The implode function joins array elements with a string.
We have integers within a string separated by comma character. We count the number of integers.
Here we split the text with the explode function. The function will cut a string into pieces whenever it finds the dot , character.
$ php expl_impl.php There are 11 numbers in the string 1,2,3,4,5,6,7,8,9,10,11
We concatenate strings with the dot operator.
$ php teams1.php Ajax Amsterdam - Inter Milano 2:3 Real Madridi - AC Milano 3:3 Dortmund - Sparta Praha 2:1
The output is not optimal. We will change it so that it looks neater.
We improve the output format with the str_pad function. It adds a specified string (in our case a space) to the left of the string, to the right or to both sides.
$ php teams2.php Ajax Amsterdam - Inter Milano 2:3 Real Madrid - AC Milano 3:3 Dortmund - Sparta Praha 2:1
We manage to give a nicer formatted output.
PHP array of chars
A string in PHP is an array of chars.
In the example, we iterate through a string and print each character’s ASCII code.
A string is defined. It contains eleven characters.
We iterate through the string with the for loop. The size of the string is determined with the strlen function. The ord function returns the ASCII value of a character. We use the array index notation to get a character.
$ php array_of_chars.php z has ASCII code 122 e has ASCII code 101 t has ASCII code 116 c has ASCII code 99 o has ASCII code 111 d has ASCII code 100 e has ASCII code 101 . has ASCII code 46 c has ASCII code 99 o has ASCII code 111 m has ASCII code 109
PHP string formatting
String formatting or string interpolation is dynamic putting of various values into a string.
We use the %d formatting specifier. The specifier expects an integer value to be passed.
$ php fruits.php There are 12 oranges and 32 apples in the basket.
In the next example, we pass a float and a string value.
The formatting specifier for a float value is %f and for a string %s .
$ php height.php Height: 172.300000 cm
We might not like the fact that the number in the previous example has 6 decimal places by default. We can control the number of the decimal places in the formatting specifier.
The decimal point followed by an integer controls the number of decimal places. In our case, the number has exactly one decimal place.
$ php height2.php Height: 172.3 cm
The following example shows other formatting options.
The first format works with hexadecimal numbers. The x character formats the number in hexadecimal notation. The o character shows the number in octal format. The e character shows the number in scientific format.
$ php formatting.php 12c 454 100101100 3.000000e+5
The next example prints three columns of numbers.
The numbers are left justified and the output is not neat.
$ php columns.php 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331
To correct this, we use the width specifier. The width specifier defines the minimal width of the object. If the object is smaller than the width, it is filled with spaces.
Now the output looks OK. Number 2 says that the first column will be 2 characters wide.
$ php columns2.php 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331
In this article, we have covered PHP strings.
PHP String
Summary: in this tutorial, you will learn about PHP strings and how to manipulate strings effectively.
Introduction to PHP strings
In PHP, a string is a sequence of characters. PHP provides you with four ways to define a literal string, including single-quoted, double-quoted, heredoc syntax, and nowdoc syntax. This tutorial focuses on the single-quoted and double-quoted strings.
To define a string, you wrap the text within single quotes like this:
$title = 'PHP string is awesome';
Code language: HTML, XML (xml)
Or you can use double quotes:
$title = "PHP string is awesome";
Code language: HTML, XML (xml)
However, you cannot start a string with a single quote and ends it with a double quote and vice versa. The quotes must be consistent.
Single-quoted strings vs. double-quoted strings
Suppose you have a variable $name .
$name = 'John';
Code language: HTML, XML (xml)
And you want to show a message that displays the following:
To do it, you can use the concatenate operator ( . ) to concatenate two strings:
$name = 'John'; echo 'Hello ' . $name;
Code language: HTML, XML (xml)
However, if you use a double-quoted string, you can place the $name variable inside the string as follows:
$name = 'John'; echo "Hello $name";
Code language: HTML, XML (xml)
When evaluating a double-quoted string, PHP replaces the value of any variable that you place inside the string. This feature is called variable interpolation in PHP.
An alternative syntax is to wrap the variable in curly braces like this:
$name = 'John'; echo "Hello ";
Code language: HTML, XML (xml)
Note that PHP doesn’t substitute the value of variables in the single-quoted string, for example:
$name = 'John'; echo 'Hello ';
Code language: HTML, XML (xml)
The output will be like this:
Hello Code language: PHP (php)
Besides substituting the variables, the double-quoted strings also accept special characters, e.g., \n , \r , \t by escaping them.
It’s a good practice to use single-quoted strings when you don’t use variable interpolation because PHP doesn’t have to parse and evaluate them for double-quoted strings.
Accessing characters in a string
A string has a zero-based index. It means that the first character has an index of 0. The second character has an index of 1 and so on.
To access a single character in a string at a specific position, you use the following syntax:
$str[index]
Code language: PHP (php)
$title = 'PHP string is awesome'; echo $title[0];
Code language: HTML, XML (xml)
Getting the length of a string
To get the length of a string, you use a built-in function strlen() , for example:
$title = 'PHP string is awesome'; echo strlen($title);
Code language: HTML, XML (xml)
Summary
- A string is a sequence of characters surrounded by single quotes or double quotes.
- PHP substitutes variables embedded in a double-quoted string.
- A string is a zero-based index. Therefore, you can access a character at a specific position in a string using the square brackets [] .
- Use the strlen() function to get the length of the string.