PHP, strings are sequences of characters, and they can be manipulated in various ways.

You can declare strings using single quotes (') or double quotes (")

There are 4 ways to specify a string literal in PHP.

1.  Single-quoted Strings:

Enclosed within single quotes (')

$singleQuotedString = 'This is a single-quoted string.';

2. Double-quoted Strings:

Enclosed within double quotes (")

$variable = "dynamic";
$doubleQuotedString = "This is a $variable string.";

3. Heredoc Syntax:

  • A way to specify a multiline string.
  • Begins with <<< followed by an identifier and ends with the identifier on a line by itself.
$heredocString = <<<EOD
This is a heredoc string.
It can span multiple lines.
EOD;

4. Nowdoc Syntax:

  • Similar to heredoc but does not interpret variables.
  • Begins with <<<' followed by an identifier and ends with the identifier on a line by itself.
$nowdocString = <<<'EOD'
This is a nowdoc string.
It does not interpret variables.
EOD;

String Concatenation:

Concatenate strings using the . operator:

$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName;  // Output: John Doe

String Length:

Use the strlen function to get the length of a string:

$str = "Hello, World!";
$length = strlen($str);
echo $length;  // Output: 13

Substring:

Extract a portion of a string using substr:

$str = "Hello, World!";
$substring = substr($str, 0, 5);  // Starting from index 0, take 5 characters
echo $substring;  // Output: Hello

String Replacement:

Replace part of a string using str_replace

$str = "I like apples.";
$newStr = str_replace("apples", "bananas", $str);
echo $newStr;  // Output: I like bananas.

String Conversion

Convert a string to lowercase or uppercase using strtolower and strtoupper

$str = "Hello, World!";
$lowercase = strtolower($str);
$uppercase = strtoupper($str);
echo $lowercase;  // Output: hello, world!
echo $uppercase;  // Output: HELLO, WORLD!

String Comparison:

Compare strings using strcmp

$str1 = "apple";
$str2 = "banana";
$result = strcmp($str1, $str2);

if ($result === 0) {
    echo "Strings are equal.";
} elseif ($result < 0) {
    echo "$str1 comes before $str2.";
} else {
    echo "$str1 comes after $str2.";
}

String Splitting:

Split a string into an array using explode

$str = "apple,orange,banana";
$fruits = explode(",", $str);
print_r($fruits);
// Output: Array ( [0] => apple [1] => orange [2] => banana )