A string is a sequence of characters, where characters can be letters, numbers, or symbols i.e., used to store and manipulate it.
A single-quoted string is a sequence of characters enclosed within single quotes (').
<?php
$singleQuotedString = 'Hello, Learners';
echo $singleQuotedString;
?>
A double-quoted string is a sequence of characters enclosed within double quotes (`”`).
<?php
$greets = 'Hello, "Learners!"';
// Double quotes allow single quotes within the string
echo "Greets: $greets". "<br>";
// Single quotes not process special characters
echo 'Greets: $greets'. "<br>";
// Single quotes allow double quotes within the string
echo 'Greets: '.$greets;
?>
Note: When using double quotes, PHP will interpret certain special characters and variables within the string, while single quotes will not interpret special characters.
Heredoc syntax (<<<) is the third way to declare strings. Heredoc define a block of text in some programming languages like PHP. It allows you to create a multi-line string without having to enclose each line in quotes.
<?php
$str = 'heredoc';
$hereStr = <<<EOT
This is a
multi-line
string using heredoc syntax.
You can include variables like this: $str
EOT;
echo $hereStr;
?>
In PHP, the string concatenation operator is a dot (.). Dot is used to concatenate two or more strings together.
<?php
$str1 = "Hello";
$str2 = "Learners";
$greet = $str1 . $str2;
echo $greet;
?>
The strlen() is the built in function used to find the length of a string.
<?php
$str = "LearnCoding";
echo strlen($str);
?>
The strops() is the built in function in PHP which is used to search for a character and string within a given string.
<?php
$str = "PHP was created by Rasmus lerdorf";
echo strpos( $str,"created");
?>
In PHP, str_replace() function is used to replace occurrences of a substring with another string within a given string.
<?php
str_replace($search, $replace, $subject);
?>
<?php
$str = "Hello Geek";
$str_new = str_replace("Geek", "Learners", $str);
echo $str_new;
?>
Php sprintf() and printf() function is used for formatting of string.
In printf() function uses format specifiers to format strings, while sprintf() function returns a formatted string instead of printing it. Replaces the percent(%) sign by variable passed as an argument. Related functions: printf(), vprintf(), vsprintf(), fprintf() and vfprintf().
<?php
$num = 2;
printf("The rank is %d", $num);
$str_sprintf = sprintf("THe rank is %d", $num);
echo $str_sprintf;
?>
Function | Uses |
substr() | It returns the subpart of a string |
strtolower() | It converts the string to lowercase |
strtoupper() | It converts the string to uppercase |
trim() | It removes whitespace and other characters from the start and end of a string |
strcmp() | It compares two strings |
number_format | It is a case-sensitive string comparison |
There are more than 50 php functions related to string & Php supports 256-character set.