PHP Strings


Strings are one of the most fundamental data types in PHP. A string is a sequence of characters, such as letters, numbers, or symbols, enclosed in either single (' ') or double (" ") quotes. Understanding strings is essential because almost every web application involves displaying, manipulating, or storing text. PHP provides a rich set of tools to handle strings efficiently.

Creating Strings in PHP

You can create strings using single quotes or double quotes:

<?php
// Single-quoted string
$singleQuote = 'Hello, World!';
echo $singleQuote . "<br>";

// Double-quoted string
$doubleQuote = "Hello, PHP!";
echo $doubleQuote;
?>
  • Single quotes treat content literally; variables inside are not parsed.

  • Double quotes allow variable interpolation, making them more flexible for dynamic content.

  • For longer text, PHP supports multi-line strings, which we will cover later.

Variable Interpolation in Strings

When using double quotes, PHP replaces variables with their values:

<?php
$name = "Vicky";
echo "Hello, $name!"; // Outputs: Hello, Vicky!
?>
  • Interpolation does not work with single quotes:

echo 'Hello, $name!'; // Outputs: Hello, $name!
  • Use curly braces {} to clearly define variable boundaries inside complex strings:

$greeting = "Welcome, {$name}Sanjana!";
echo $greeting; // Avoids ambiguity

String Concatenation

Strings can be combined using the dot operator (.):

<?php
$firstName = "Vicky";
$lastName = "Sanjana";

// Concatenate strings
$fullName = $firstName . " " . $lastName;
echo "Full Name: " . $fullName;
?>
  • Concatenation is necessary when using single quotes or combining multiple strings.

  • It allows building dynamic messages for output or storage.

  • You can also concatenate strings with numbers:

$age = 25;
echo $name . " is " . $age . " years old.";

Common String Functions

PHP provides a wide range of built-in functions for string manipulation.

1. strlen() – String Length

<?php
$text = "PHP Tutorial";
echo "Length: " . strlen($text); // Outputs: 12
?>
  • Counts all characters, including spaces and punctuation.

2. strtoupper() and strtolower()

<?php
echo strtoupper("hello"); // Outputs: HELLO
echo strtolower("HELLO"); // Outputs: hello
?>
  • Useful for standardizing text or formatting user input.

3. substr() – Extract Substrings

<?php
$text = "PHP Tutorial";
echo substr($text, 4, 8); // Outputs: Tutorial
?>
  • Extracts a part of the string starting from a position for a specified length.

4. trim() – Remove Whitespace

<?php
$text = "   Hello World!   ";
echo trim($text); // Removes spaces from both ends
?>
  • Helps clean user input before storing in a database.

5. str_repeat() – Repeat Strings

<?php
echo str_repeat("PHP! ", 3); // Outputs: PHP! PHP! PHP!
?>
  • Useful for creating repeated patterns or messages.

6. ucfirst() – Capitalize First Letter

<?php
$text = "hello world";
echo ucfirst($text); // Outputs: Hello world
?>
  • Helps in formatting user-friendly text or titles.

7. strpos() – Find Position of a Substring

<?php
$sentence = "PHP is fun";
$position = strpos($sentence, "fun");
echo "Position of 'fun': " . $position;
?>
  • Returns the index of the first occurrence of a substring, starting from 0.

8. str_replace() – Replace Text

<?php
$text = "I love PHP";
$newText = str_replace("PHP", "Coding", $text);
echo $newText; // Outputs: I love Coding
?>
  • Replaces all occurrences of a substring with a new value.

Multi-line Strings

PHP allows multi-line strings using heredoc or nowdoc syntax.

Heredoc

<?php
$heredoc = <<<EOD
This is a multi-line string.
Variables like $name will be parsed.
You can write long text without quotes.
EOD;

echo $heredoc;
?>

Nowdoc

<?php
$nowdoc = <<<'EOD'
This is a nowdoc string.
Variables like $name will not be parsed.
Useful for literal text blocks.
EOD;

echo $nowdoc;
?>
  • Heredoc acts like double quotes; variables are interpolated.

  • Nowdoc acts like single quotes; variables are literal.

Escaping Characters

Special characters can be included using backslash \:

<?php
echo "He said, \"Hello World!\"<br>"; // Double quotes inside double quotes
echo 'It\'s a beautiful day!<br>';    // Single quote inside single quotes
echo "Line1\nLine2<br>";              // New line character
?>
  • Use <br> for line breaks in the browser.

  • Escaping is essential to avoid syntax errors.

String Comparison

Strings can be compared using operators or functions:

<?php
$str1 = "Hello";
$str2 = "hello";

// Case-sensitive
if ($str1 == $str2) {
    echo "Equal";
} else {
    echo "Not equal"; // Case-sensitive
}

// Case-insensitive
if (strcasecmp($str1, $str2) == 0) {
    echo "Equal ignoring case";
}
?>
  • == is case-sensitive.

  • strcasecmp() ignores case differences.

Summary of the Tutorial

  • Strings are sequences of characters enclosed in single or double quotes.

  • Double quotes allow variable interpolation; single quotes are literal.

  • Concatenate strings using the dot (.) operator.

  • PHP provides many string functions: strlen(), strtoupper(), strtolower(), substr(), trim(), str_repeat(), ucfirst(), strpos(), str_replace().

  • Multi-line strings can be created with heredoc or nowdoc.

  • Escape special characters using \.

  • Compare strings with operators or functions for case-insensitive checks.

Mastering strings is crucial for text manipulation, dynamic content, user input handling, and web application development in PHP.


Practice Questions

  1. Create a PHP script that declares a string variable $greeting = "Hello World" and prints it using echo. Add a comment explaining it is a string.

  2. Declare a variable $name = "Vicky" and print “Hello, Vicky!” using double quotes with echo. Include a comment explaining variable interpolation.

  3. Write a PHP script that concatenates $firstName = "Vicky" and $lastName = "Sanjana" to print the full name. Include a comment explaining the dot operator.

  4. Create a PHP script that uses strlen() to print the length of the string $text = "PHP Tutorial". Add a comment describing the function.

  5. Write a PHP file that converts the string $word = "hello" to uppercase using strtoupper() and lowercase using strtolower(). Include comments explaining each function.

  6. Use substr() to extract “Tutorial” from $text = "PHP Tutorial" and print it with a comment explaining the start and length parameters.

  7. Create a PHP script that removes whitespace from the string $text = " Hello PHP " using trim() and prints the result. Include a comment explaining the function.

  8. Write a PHP script that prints a multi-line message using heredoc and include a variable inside it. Add comments explaining interpolation.

  9. Create a PHP script that replaces “PHP” with “Coding” in $sentence = "I love PHP" using str_replace() and print the result. Include a comment explaining the function.

  10. Write a PHP file that compares two strings $str1 = "Hello" and $str2 = "hello" both case-sensitively and case-insensitively, and prints the results. Include comments explaining the comparison.


Go Back Top