PHP String
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.
- single quoted
- double quoted
- heredoc syntax
- newdoc syntax (since PHP 5.3)
A string is a sequence of characters, like ‘PHP supports string operations.’ A string in PHP as an array of bytes and an integer indicating the length of the buffer.
To cut a part of a string and return it as a new string, we can use the substr
function:
$filename = "image.png"; $extension = substr($filename, strlen($filename) - 3); echo "The extension of the file is $extension";
<?php $str1='Hello text multiple line text within single quoted string'; $str2='Using double "quote" directly inside single quoted string'; $str3='Using escape sequences \n in single quoted string'; echo "$str1 <br/> $str2 <br/> $str3"; ?>
- “\n” is replaced by a new line
- “\t” is replaced by a tab space
- “\$” is replaced by a dollar sign
- “\r” is replaced by a carriage return
- “\\” is replaced by a backslash
- “\”” is replaced by a double quote
- “\’” is replaced by a single quote
- The string starting with a dollar sign(“$”) are treated as variables and are replaced with the content of the variables.
<?php class heredocExample{ var $demo; var $example; function __construct() { $this->demo = 'DEMO'; $this->example = array('Example1', 'Example2', 'Example3'); } } $heredocExample = new heredocExample(); $name = 'Gunjan'; echo <<<ECO My name is "$name". I am printing some $heredocExample->demo example. Now, I am printing {$heredocExample->example[1]}. It will print a capital 'A': \x41 ECO; ?>