String in PHP


Share

A string is a collection of characters. String is one of the data types supported by PHP.
The string variables can contain alphanumeric characters.
1. You declare variable and assign string characters to it.
2. You can directly use them with echo statement.
3. String are language construct, it helps capture words.

A string literal can be specified in four different ways:

1. Single quoted
2. Double quoted
3. Heredoc syntax
4. Nowdoc syntax

1 )Single quotes

    <?php
    echo 'This is a my first page';
    ?> 
    OUTPUT:
    This is a my first page

2) Double quotes

The double quotes are used to create relatively complex strings compared to single quotes.

<?php
$name = 'John';
echo "$name is good boy in class";
?>
    OUTPUT:
    John is good boy in class

3) Heredoc

A third way to delimit strings is the heredoc syntax: (<<<). After this operator, an identifier is provided, then a newline.

<?php
class foo {
    public $bar = <<<EOT
bar
EOT;
?>

4) Nowdoc

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, e.g. <<<'EOT'.

<?php
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;
?>
    OUTPUT:
    Example of string spanning multiple lines
    using nowdoc syntax. Backslashes are always treated literally,
    e.g. \\ and \'.

String has a various functions:

strlen(), strpos(), substr(), strchr(), strcmp(), strcoll(), strtr(), strrev(), strcasecmp() etc.

String Concatenations

To concatenation two string variables we can use dot(.) operator.

<?php
$var1 = "Hello";
$var2 = "World";
echo $var1. "" .$var2;
?>
    OUTPUT:
    Hello World

Strlen() Function

Strlen() function is usde to find the length of string.

<?php
    echo strlen("Hello World");
?>
    OUTPUT:
    11

strpos() function

Strpos() function is used to search for a string or character within a string. If match is found in the string, this function will return the position of the first match.

<?php
echo strpos("Hello World", "World");
?>
    OUTPUT:
    6 

Substr() Function

The substr() function returns a part of a string.

syntax of substr()
substr(string,start,length);

<?php
echo substr("Hello world",10);
?>