Strings in PHP
Strings in PHP
PHP string is a sequence of characters i.e., used to store and manipulate text. PHP supports
only 256-character set and so that it does not offer native Unicode support. There are 4
ways to specify a string literal in PHP.
1. single quoted
2. double quoted
3. heredoc syntax
4. newdoc syntax (since PHP 5.3)
Single Quoted
We can create a string in PHP by enclosing the text in a single-quote. It is the
easiest way to specify string in PHP.
For specifying a literal single quote, escape it with a backslash (\) and to specify a
literal backslash (\) use double backslash (\\). All the other instances with backslash
such as \r or \n, will be output same as they specified instead of having any special
meaning.
Following some examples to understand the single quoted PHP String in a better way:
Example 1
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
We can store multiple line text, special characters, and escape sequences in a single-
quoted PHP string.
Double Quoted
In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.
Example 2
1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>
Output:
Number is: 10
Example
Return the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
Count the number of word in the string "Hello world!":
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
Example
Search for the text "world" in the string "Hello world!":
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello
Dolly!
?>