PHP String Handling



PHP String :

In PHP String is collection or sequence of the characters. String is written in double quotes. String can be created by the combination of any characters such as alphanumeric or any special symbols. Consider the following example –

$str1 = "String Example";
$str2 = "Another String Example";
$str3 = ""; // a string with zero characters

Now Consider the example of the PHP String –

<html>
<body>
<?php

$languageName = "PHP";
print($languageName);

$languageName = 'Java';
print($languageName);

?>
</body>
</html>

Output :

PHP Java

In the above example, In the first statement we have used double quotes to assign the string to the variable. Similarly we can use single quote. Consider the below line of code –

$nameOfFarm = 'Sanchin's farm';
print($nameOfFarm);

In the above example we have used single quotes inside the string. Then it will throw below error –
Parse error syntax error unexpected

Using Escape Sequences :

Consider the following table for escape sequences –

Escape Sequence Explanation
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)

Concatenate Strings :

If we need to concatenate two strings then we can use dot operator to concatenate the two strings. Consider the below example –

$personName = "Sachin " . "Tendulkar";
print($personName);

Using above statement, we can concatenate two strings.

Using HTML Tags inside print :

Consider the below example, In the below example we have used HTML tag inside the string variable –

<?php
$personName = "Sachin <br />" . "Tendulkar";
print($personName);
?>

Output of the above program will be like this –

Sachin 
Tendulkar