String Handling in PHP – Working with Text

What is a String in PHP?

A string is a sequence of characters used to represent text in PHP. It can include letters, numbers, symbols, or even spaces.

Strings are one of the most commonly used data types in PHP — whether you’re printing messages, validating form input, creating email templates, or building APIs.

Declaring Strings in PHP

Strings can be declared using:

  • Single quotes (') – Faster but doesn’t parse variables
  • Double quotes (") – Parses variables and escape sequences

Example:

PHP
$name = 'Jay';
echo 'Hello $name';   // Output: Hello $name
echo "Hello $name";   // Output: Hello Jay

Concatenation – Joining Strings in PHP

You can join strings using the dot (.) operator.

Example:

PHP
$firstName = "John";
$lastName = "Doe";

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

Concatenation with .=

PHP
$message = "Hello";
$message .= ", world!";
echo $message; // Output: Hello, world!

Common String Functions in PHP

PHP offers many built-in string functions for manipulation. Here are the most frequently used:

1. strlen() – String Length

PHP
echo strlen("ScriptBuzz"); // Output: 10

2. strtoupper() and strtolower()

PHP
echo strtoupper("php");   // Output: PHP
echo strtolower("SCRIPT"); // Output: script

3. ucfirst() and ucwords()

PHP
echo ucfirst("jay");         // Output: Jay
echo ucwords("jay patel");   // Output: Jay Patel

4. substr() – Extract a part of a string

PHP
echo substr("ScriptBuzz", 0, 6); // Output: Script

5. str_replace() – Replace text in a string

PHP
echo str_replace("world", "PHP", "Hello world"); // Output: Hello PHP

6. strpos() – Find position of substring

PHP
echo strpos("Learn PHP at ScriptBuzz", "PHP"); // Output: 6

Multiline Strings – Heredoc & Nowdoc

When working with blocks of text, use Heredoc or Nowdoc.

Heredoc (supports variables):

PHP
$name = "Jay";
$text = <<<EOD
Hello $name,
Welcome to ScriptBuzz!
EOD;

echo $text;

Nowdoc (treats as plain text):

PHP
$text = <<<'EOD'
This is plain text. No variables will be parsed.
EOD;

Trimming and Cleaning Strings

trim() – Removes whitespace from both ends

PHP
$name = "  Jay  ";
echo trim($name); // Output: Jay

ltrim() and rtrim()

PHP
echo ltrim("   hello"); // Removes left spaces
echo rtrim("hello   "); // Removes right spaces

Real-World Examples of String Handling

1. Format Full Name

PHP
$first = "john";
$last = "DOE";

$full = ucwords(strtolower($first . " " . $last));
echo $full; // Output: John Doe

2. Mask an Email Address

PHP
$email = "hello@example.com";
$hidden = substr($email, 0, 2) . "****" . strstr($email, "@");
echo $hidden; // Output: he****@example.com

3. Validate if String Contains a Keyword

$input = "I love PHP programming";

if (strpos($input, "PHP") !== false) {
  echo "You're a PHP developer!";
}

Common Mistakes with Strings

  • Using single quotes when you want variable interpolation
  • Forgetting that strpos() returns 0 for the first position (not false!)
  • Not trimming user input before saving or comparing
  • Confusing string functions with similar names (strstr() vs strpos())

Best Practices

  • Use trim() on user-submitted form data
  • Use double quotes only when necessary (to improve performance)
  • Combine multiple string functions for formatting
  • Validate and sanitize strings before using them in queries or output
  • Escape special characters for HTML using htmlspecialchars()

Notes:

  • Strings are used to store and manipulate textual data in PHP
  • You can concatenate strings using ., and include variables with double quotes
  • PHP offers powerful functions to work with, format, and search strings
  • Clean and trim inputs to ensure reliability
  • Heredoc/Nowdoc help with multiline string output

Practice Tasks

Task 1: Welcome Message Generator
Create a function that takes a name and returns:

CSS
Hello, [Name]! Your name has [X] letters.

Task 2: Case Converter
Take a sentence and:

  • Convert to lowercase
  • Convert to uppercase
  • Capitalize first letter of each word

Task 3: Password Masking
Create a function that replaces all but the last 3 characters of a string with *.
Example: secretpassword*********ord