×
☰ See All Chapters

PHP Strings

String is group of any characters. String can contain any alphabets, numbers, special characters.

In PHP you can declare string variable in 3 ways.

  • Using single quotes 

  • Using double quotes 

  • Using heredoc syntax 

String using single quotes

Strings are created inside single quotes.

<?php

$name = 'Manu Manjunatha';

?>

String using double quotes

Strings are created inside double quotes.  String using double quotes supports interpolation, means if you place a variable within the double quotes, it returns the value of that variable. You can place the variable name directly inside double quotes or you can use interpolation syntax ${variableName} as below example.

<?php

$name = 'Manu Manjunatha';

 

echo "My name is $name </br>";

echo 'My name is $name </br>';

echo "My name is ${name} </br>";

echo 'My name is ${name} </br>';

 

?>

php-strings-0
 

String using heredoc syntax

The heredoc syntax is useful for multi-line strings and avoiding quoting issues.  Below is the heredoc syntax:

$variable = <<<nameOfString

//contents

nameOfString;

 

String using heredoc syntax supports interpolation, means if you place a variable within a string, it returns the value of that variable. You can place the variable name directly inside double quotes or you can use interpolation syntax ${variableName} as below example.

heredoc string example:

<?php

$author= "Manu Manjunatha";

$tablename = "Student";

$id = 100;

 

$sql = <<<SQL

select *

  from $tablename

 where studenid = $id

   and studentname = $author

SQL;

 

 

$html = <<<HTML

</br><b>Welcome to www.java4coding.com</b> </br>

<p>Author: ${author}</p>

<p>Author Id: ${id}</p>

HTML;

 

echo $sql."</br>";

echo $html;

?>

php-strings-1
 

PHP String Functions

Function

Description

strlen()

Return the length of a String.

<?php
echo strlen("Hello world!"); // outputs 12
?>

str_word_count()

Count words in a String

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev()

Reverse a String

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos()

Search for a text within a String

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>

str_replace()

Replace text within a String

<?php
echo str_replace("world", "Manu M", "Hello world!"); // outputs Hello Manu M!
?>

String Concatenation

There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.

<?php

$a = "Hello ";

$b = $a . "World!";

echo $a."</br>";

 

$x = "Hello ";

$x .= "World!";

echo $x;

?>

php-strings-2
 

All Chapters
Author